本文实例讲述了Android编程实现控件不同状态文字显示不同颜色的方法。分享给大家供大家参考,具体如下:
方式一:
第一要选择的控件
1
2
3
4
5
6
7
|
< TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/close_time_display" android:layout_marginRight = "20dp" android:text = "@string/default_time" style = "@style/item_content_text_style" /> |
style是自定义的风格,对应的xml文件如下:
1
2
3
4
5
|
< style name = "item_content_text_style" > < item name = "android:textSize" >26sp</ item > < item name = "android:duplicateParentState" >true</ item > < item name = "android:textColor" >@drawable/textcolor_yellow_selector</ item > </ style > |
textColor中的textcolor_yellow_selector如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<? xml version = "1.0" encoding = "utf-8" ?> < selector xmlns:android = "http://schemas.android.com/apk/res/android" > < item android:state_pressed = "true" android:color = "@color/yellow" /> < item android:state_focused = "true" android:color = "@color/yellow" /> < item android:state_selected = "true" android:color = "@color/yellow" ></ item > < item android:color = "@color/white" /> </ selector > |
实现方式二:ColorStateList文字变色
API
Windows平台VC,对于不同的按钮状态,采用不同的颜色显示文字,实现起来比较复杂,一般都得自绘按钮。但是Android里面实现起来非常方便。
我们首先添加一个ColorStateList资源XML文件,XML文件保存在res/color/button_text.xml:
1
2
3
4
5
6
7
8
|
<? 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 > |
1
2
3
4
5
6
|
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); //设置按钮文字颜色 } |
或者可以这样:
1
2
3
4
5
6
7
|
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 } |
最后附上所有可能出现的状态:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<? 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 > |
希望本文所述对大家Android程序设计有所帮助。