Android 代码里动态设置TextView/Button等的文字颜色Seletor

 

 //设置文本颜色
     btn.setTextColor(getResources().getColorStateList(R.color.find_tab_btn_selector));
//设置背景
     btn.setBackground(this.getResources().getDrawable(R.drawable.selector_tab_txt_bottom));
//设置底边图片
     Drawable drawable = getResources().getDrawable(R.drawable.selector_tab_txt_bottom);
     // 这一步必须要做,否则不会显示.
     drawable.setBounds(0, 0, drawable.getMinimumWidth(), 5);
     btn.setCompoundDrawables(null, null, null, drawable);
 以下是我在/res/color文件夹里给button设置的文字颜色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>
 
 mBtnDownAndOpen.setText(DOWNLOAD_OPEN);  //设置button文字
 mBtnDownAndOpen.setTextColor(mContext.getResources().getColorStateList(R.color.networkdata_btn_open_txtcolor_selector));   //设置button文字颜色
 mBtnDownAndOpen.setBackground(mContext.getResources().getDrawable(R.drawable.networkdata_btn_open_selector));    //设置button背景
  文字颜色的seletor在代码里的显示形式是ColorStateList,而res/color放的就是ColorStateList资源XML文件,getColor只能读取单个的color。

猜你喜欢

转载自ch-kexin.iteye.com/blog/2314895