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.若枚舉類顯式的定義了帶參數的構造器, 則在列出枚舉值時也必須對應的傳入參數


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