在自定义view的时候,通常会自定义一些属性,为了便于统一使用,在style文件中把自定义属性赋值。但是我却在自定义view中,取不到style中设置的值,如果在xml中设置属性值却能正常获取,这是为什么呢?
在res/attrs中自定义属性attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TabButton">
<attr name="tab_text" format="reference|string"/>
<attr name="tab_drawable" format="reference"/>
<attr name="tab_text_color" format="color"/>
<attr name="tab_text_size" format="dimension"/>
</declare-styleable>
</resources>
在res/color中新建text_tab_button_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/blue" android:state_pressed="true"/>
<item android:color="@color/blue" android:state_selected="true"/>
<item android:color="@color/text_gray"/>
</selector>
在res/values/styles.xml定义:
<resources >
<style name="style_tab_button">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">match_parent</item>
<item name="android:layout_weight">1</item>
<item name="tab_text_size">@dimen/p22</item>
<item name="tab_text_color">@color/text_tab_button_selector</item>
</style>
</resources>
在自定义view 中获取属性值:
TypedArray typedArray = getContext().obtainStyledAttributes(attrs,
R.styleable.TabButton);
mDrawable = typedArray.getDrawable(R.styleable.TabButton_tab_drawable);
contentText = typedArray.getString(R.styleable.TabButton_tab_text);
color = typedArray.getColorStateList(R.styleable.TabButton_tab_text_color); // text多状态要用ColorStateList
size = typedArray.getDimensionPixelSize(R.styleable.TabButton_tab_text_size, 30);
typedArray.recycle();
我一开始的时候获取不到style中的自定义属性值,是因为我获取TypedArray的方法有问题:
TypedArray typedArray = getContext().getResources().obtainAttributes(attrs,
R.styleable.TabButton);