前言
今天遇到個很蛋疼的問題富弦,下載時,多個按鈕共用一個button氛驮,也就是不同下載狀態(tài)下腕柜,button的背景以及字體顏色都不一樣,結(jié)果自己挖了坑把自己埋進去了。
以下是我在/res/color文件夾里給button設(shè)置的文字顏色seletor:networkdata_btn_open_txtcolor_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ffffff" android:state_pressed="true"></item>
<item android:color="#ffffff" android:state_selected="true"></item>
<item android:color="#f88b00"></item>
</selector>
坑盏缤?
在代碼里設(shè)置顏色seletor砰蠢,以為在代碼里直接調(diào)用 button.setTextColor(int colorValue) 就可以了,結(jié)果運行效果讓我傻眼了唉铜。
mBtnDownAndOpen.setText(DOWNLOAD_OPEN); //設(shè)置button文字
mBtnDownAndOpen.setTextColor(mContext.getResources().getColor(R.color.networkdata_btn_open_txtcolor_selector)); //設(shè)置button文字顏色
mBtnDownAndOpen.setBackground(mContext.getResources().getDrawable(R.drawable.networkdata_btn_open_selector)); //設(shè)置button背景
郁悶的是台舱,只能讀取到?jīng)]獲取焦點時的色值,也就是 <item android:color="#f88b00"></item> 潭流,其他狀態(tài)獲取不到竞惋。
如何填坑?
采用
mBtnDownAndOpen.setTextColor(mContext.getResources().getColorStateList(R.color.networkdata_btn_open_txtcolor_selector));
為button設(shè)置文字顏色灰嫉。
區(qū)別在于:改之前用的是getColor拆宛,改之后用的是getColorStateList
WHY?
文字顏色的seletor在代碼里的顯示形式是ColorStateList,而res/color放的就是ColorStateList資源XML文件讼撒,getColor只能讀取單個的color浑厚。
轉(zhuǎn)載:http://blog.csdn.net/zhangshao45612/article/details/49784997