ColorStateList按钮文字变色

Windows平台VC,对于不同的按钮状态,采用不同的颜色显示文字,实现起来比较复杂,一般都得自绘按钮。但是Android里面实现起来非常方便。

我们首先添加一个ColorStateList资源XML文件,XML文件保存在res/color/button_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>

Button btn=(Button)findViewById(R.id.btn);
Resources resource=(Resources)getBaseContext().getResources();
ColorStateList csl=(ColorStateList)resource.getColorStateList(R.color.button_text);
if(csl!=null){
btn.setTextColor(color_state_list);//设置按钮文字颜色
}


或者也可以这样:

XmlResourceParser xpp=Resources.getSystem().getXml(R.color.button_text);
try {
ColorStateList csl= ColorStateList.createFromXml(getResources(),xpp);
btn.setTextColor(csl);
} catch (Exception e) {
// TODO: handle exception
}


最后附上所有可能出现的状态:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>


[img]http://dl.iteye.com/upload/attachment/518724/d3e39a64-e9e0-3f98-bf7b-d98bdb956431.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值