android源码解析(2)--如何读取自定义属性

         自定义view当中肯定会用到自定义属性,那么如何读取使用自定义属性呢?先推荐大神的文章 http://blog.csdn.net/lmj623565791/article/details/24252901  但是呢,他这篇文章里有一个地方没说太明白,就是如何使用枚举类型的自定义属性,下面就通过阅读源码模仿Imageview的scaleType来写的如何读取自定义枚举类型属性:

        1.写attrs文件,自定义属性:

<resources>
    <attr name="style" format="enum" />
    <attr name="mycolor" format="color"/>

    <declare-styleable name="TestView">
        <attr name="mycolor"/>
        <attr name="my_style">
            <enum name="AAAA" value="0" />
            <enum name="BBBB" value="1" />
            <enum name="CCCC" value="2" />
            <enum name="DDDD" value="3" />
        </attr>
    </declare-styleable>
</resources>
2.xml文件中使用:

       <com.hawk.android.camera.apptestdemo.TestView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:background="@color/colorPrimary"
        custom:my_style="BBBB"
        custom:mycolor="@color/colorAccent" />
3.构造器中读取属性值,这里重点看枚举类型:

   public class TestView extends View {
    private MyStyle mMyStyle;
    private int mColor;
    private static final MyStyle[] MY_STYLES = {
            MyStyle.AAAA,
            MyStyle.BBBB,
            MyStyle.CCCC,
            MyStyle.DDDD
    };
    
    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TestView, defStyleAttr, 0);
        mColor = typedArray.getColor(R.styleable.TestView_mycolor, Color.RED);
        int anInt = typedArray.getInt(R.styleable.TestView_my_style, -1);
        if (-1 != anInt) {
            mMyStyle = MY_STYLES[anInt];
        }
        typedArray.recycle();
    }

    public enum MyStyle {
        AAAA(0),
        BBBB(1),
        CCCC(2),
        DDDD(3);

        MyStyle(int ni) {
            nativeInt = ni;
        }

        final int nativeInt;
    }
}

细节不用讲解,一看就懂。
1.枚举类的使用 private final 修饰的属性应该在构造器中为其赋值
2.若枚举类显式的定义了带参数的构造器, 则在列出枚举值时也必须对应的传入参数


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章