Windows platform VC, for different button states, the use of different color display text, the implementation of more complex, generally have to draw the button. But Android is easy to implement.
We first add a colorstatelist resource XML file, and the XML file is saved in Res/color/button_text.xml:
Java code
- <?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>
Java code
- 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 button text color
- }
Or you can do this:
Java code
- 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 the possible statuses:
Java code
- <?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>
Transferred from: http://blog.csdn.net/ganlijianstyle/article/details/7593812
--------------------------------------------------------------------------------------------------------------- ---------------------------
Currentbutton.settextcolor (R.color.white);
The ID of this direct-value color goes in, and the text is found to be black, so you need to use SetTextColor (colorstatelist colors) method to pass in the Colorstatelist object
Colorstatelist whitecolor=getresources (). Getcolorstatelist (R.color.white);
Currentbutton.settextcolor (Whitecolor);
So the text can change color.
The Colorstatelist object can be defined in XML and used like a color, which can change color in real time based on the state of the View object it is applied to. For example, a button can exist in multiple states (pressed, focused, or other), and if you use Colorstatelist, you can provide different colors for each of its states.
Original: http://blog.csdn.net/meizhen51/article/details/6303612