自定義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;
}
}
細節不用講解,一看就懂。