Android主题应用

直接进入正文!

要设置主题首先需要定义一个自定义的属性值,

attrs.xml

<resources>
    <declare-styleable name="my_styleable">
        <attr name="colorValue" format="color" />
        <attr name="backValue" format="reference" />
    </declare-styleable>

</resources>

然后,定义对应的style。

styles.xml

    <style name="Bule" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="colorValue">@color/bule_bg</item>
        <item name="backValue">@drawable/icon_bule_back</item>
    </style>
    
OK,现在就可以用了!

main.xml

<TextView
                android:id="@+id/tv_test"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="测试文字"
                android:textColor="?attr/colorValue"
                android:textSize="28sp" />
当然,在真正使用它的时候还需要在Activity的onCreate方法里设置:

		setTheme(R.style.Bule);
                //注意,一定要在setContentView之前设置主题
		setContentView(R.layout.activity_main);
设置就这么完了。看看效果吧~

现在有一个问题就是,当我们做了2款以上的主题,如果需求是获取当前主题的某一个值(比如获取当前id为:tv_test的那个textColor值),怎么办呢?

很简单,2句代码:

TypedArray ta = getTheme().obtainStyledAttributes(R.styleable.my_styleable);
//注:这个R.styleable.my_styleable_colorValue其实是自动生成的
int color = ta.getColor(R.styleable.my_styleable_colorValue, 0);
//对了,别忘了加上下面这句
ta.recycle();

OK。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值