Windows platform VC, for different button states, uses different colors to display text, which is more complicated to implement, and generally has to draw buttons by itself. But it is very convenient to implement in Android.
We first add a ColorStateList resource XML file, the XML file is saved in 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); //Set the button text color
- }
Or it can be like this:
- 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
- }
Finally, attach all possible states:
- <?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>