Tuesday, August 14, 2012

사용자 정의 뷰와 R.styleable

사용자 정의 뷰에서 사용할 attribute를 정의하고 사용하기



1.사용자 정의 뷰에서 사용할 attribute를 attrs.xml에 정의하기


   <resources>
      <declare-styleable name="FramedImageView">
         <attr format="reference" name="placeHolder" />
      </declare-styleable>
   </resources>

위의 코드 처럼 작성을 하면 R.java 파일에는 다음과 같은 레퍼런스가 작성이 된다.

   public static final class styleable {
      public static final int[] FramedImageView = { ... };
      public static final int FramedImageView_placeHolder = 0;
   }

객체 타입을 reference로 format을 정하는 것처럼 그 외의 타입에 대한 attribute 추가고 가능하다.

   <attr format="integer" name="testInteger" />
   <attr format="boolean" name="testBoolean" />

을 추가하면 당연히 R.java 파일에도 아래와 같은 레퍼런스가 각각 추가되겠지.

   public static final int FramedImageView_testInteger = 1;
   public static final int FramedImageView_testBoolean = 2;



2.레이아웃 xml 파일에서 attribute 값을 지정하고


다음으로 레이아웃 xml파일에서 각각의 attribute 값에 원하는 값을 지정해 줄 수가 있어. 아래 코드에서 붉게 표시된 부분을 주의 깊게 볼 것.


   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns: how2develop="http://schemas.android.com/apk/res/com.how2develop"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical" >

       <com.how2develop.widget.FramedImageView
           android:id="@+id/frameImageView"
           android:layout_width="200dp"
           android:layout_height="200dp"
           android:layout_centerVertical="true"
           android:layout_gravity="center"
           android:layout_margin="10dp"
           how2develop:placeHolder="@drawable/blankImage" />


3.뷰 클래스의 생성자에서 해당 값을 읽어 오면 된다


사용자 정의 뷰 클래스에서 이제 해당 attribute를 읽어오면 되는데, 아래의 코드는 ImageView를 상속하는 사용자 정의 뷰 클래스를 작성하면서 위 1,2 과정을 거치면서 정의하고 세팅한 attribute 값을, 뷰 클래스의 생성자에서 읽어오는 코드이다.


          public FramedImageView(Context context, AttributeSet attrs) {
   super(context, attrs);

   TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FramedImageView, 0, 0);
   placeHolder = a.getDrawable(R.styleable.FramedImageView_placeHolder);

   a.recycle();
   }


obtainStyledAttributes()로 획득되는 TypedArray 타입에는 위에서 호출된 getDrawable()외에도 attribute값을 읽는 (타입에 따른) 다양한 메소드가 제공되니 꼭 API을 보고 눈으로 익히는 게 좋을 듯 하다.

그리고, 불러온 후에는 recycle() 메소드를 호출해 주는 것을 잊지 말자. 그래야 할당되어 있던 메모리를 풀(pool)에 즉시 돌려줘서 garbage collection이 될 때까지 기다릴 필요가 없게 되니까.



No comments:

Post a Comment