Demo
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:id="@+id/btn"
android:layout_centerInParent="true"
android:textSize="16sp"
android:background="#07B226"
android:textColor="@color/textcolor"
android:text="点击" />
</RelativeLayout>
textcolor.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="#164869"
android:state_pressed="true"></item>
<item android:color="#ffffff"
android:state_pressed="false"></item>
</selector>
运行
ColorStateList资源
资源路径
res/color/filename.xml
资源的使用
在代码中使用:R.color.filename
在XML中使用:@[package:]color/filename
语法
<?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>
标签&标签属性
<selector>
根标签,包含一个或多个<item>元素。
<item>
定义特定状态的color,必须是的子元素。
android:color 属性值为16进制颜色。
- #RGB
- #ARGB
- #RRGGBB
- #AARRGGBB
android:state_pressed
属性值为Boolean类型。“true”表示按下状态使用(例如按钮按下);“false”表示非按下状态使用。
android:state_focused
属性值为Boolean类型。“true”表示聚焦状态使用;“false”表示非聚焦状态使用。
android:state_selected
属性值为Boolean类型。“true”表示选中状态使用(例如Tab打开);“false”表示非选中状态使用。
android:state_checkable
属性值为Boolean类型。“true”表示可勾选状态时使用;“false”表示非可勾选状态使用。(只对能切换可勾选—非可勾选的构件有用。)
android:state_checked
属性值为Boolean类型。“true”表示勾选状态使用;“false”表示非勾选状态使用。
android:state_enabled
属性值为Boolean类型。“true”表示可用状态使用(能接收触摸/点击事件);“false”表示不可用状态使用。
android:window_focused
属性值为Boolean类型。“true”表示应用程序窗口有焦点时使用(应用程序在前台);“false”表示无焦点时使用(例如Notification栏拉下或对话框显示)。
注意事项
ColorStateList中第一个匹配当前状态的item会被使用。因此,如果第一个item没有任何状态特性的话,那么它将每次都被使用,这也是为什么默认的值必须总是在最后。