Android解决style文件不能使用自定义属性

在自定义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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值