首先添加一个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"/>
- <item android:state_focused="true" android:color="#ff0000ff"/>
- <item android:color="#ff000000"/>
- </selector>
- Button btn=(Button)findViewById(R.id.btn);
- Resources resource=(Resources)getBaseContext().getResources();
- ColorStateList csl=(ColorStateList)resource.getColorStateList(R.color.button_text);
- btn.setTextColor(csl);//设置按钮文字颜色