2013년 3월 19일 화요일

android - custom view tip

View 나 ViewGroup 또는 그의 Subclass에서 상속받아 자신만의 View를 구현하고자 한다면 다음과 같은 생성자를 구현해야 한다.

생성자(Context context);

생성자(Context context, AttributeSet attrs);

생성자(Context context, AttributeSet attrs, int defStyle);


커스텀 뷰를 layout xml에서 사용할 경우 두번째나 세번째 생성자가 호출된다.
layout xml의 element에 설정한 attribute(속성)은 AttributeSet로 전달된다.
이때 커스텀 뷰에 자신만의 속성을 사용하고자 한다면 다음과 같은 절차를 따른다.

테스트 예
  • packageName : com.test.app
  • custom view class name : MyCustomView

1. values/attrs.xml에 속성을 설정한다.

<resources>
    <declare-styleable name="my_custom_view" >
        <attr name="animation_duration" format="integer" />
        <attr name="position">
            <enum name="top" value="0" />
            <enum name="bottom" value="1" />
            <enum name="left" value="2" />
            <enum name="right" value="3" />
        </attr>
    </declare-styleable>
...
</resources>

2. layout xml에 xmlns를 선언하고 해당 속성을 적용한다.

<LinearLayout
xmlns:my_custom_view="http://schemas.android.com/apk/res/com.test.app"
android:layout_width="match_parent"
android:layout_height="match_parent"
                android:gravity="center"
>
    <com.test.app.MyCustomView
        android:layout_width="300dip"
        android:layout_height="200dip"
        my_custom_view:animation_duration="1000"
        my_custom_view:position="top"
        />

</LinearLayout>

3. 구현 클래스에서 해당 속성값을 가져와 적용한다.

public MyCustomView(Context context, AttributeSet attrs) {
    // 커스텀 속성 처리
    String namespace = "http://schemas.android.com/apk/res/com.test.app"
    int defaultAnimDur = 500;
    int animationDuration = attrs.getAttributeIntValue(namespace, "animation_duration", defaultAnimDur);
    String positionStr = attrs.getAttributeValue(namespace, "position");
    
    // android 기본 속성 처리
    namespace = "http://schemas.android.com/apk/res/android"
    int layoutWidth = attrs.getAttributeIntValue(namespace, "layout_width", 0);
    int layoutHeight = attrs.getAttributeIntValue(namespace, "layout_height", 0);
}




댓글 없음:

댓글 쓰기