当我们开发中,经常用到选择器(Google官方名称为:StateListDrawable)。当控件状态(State)改变时,比如,被点击、选中等,我们要改变他的某些样式(一般是背景或者文字颜色)。
XML文件中的selector节点,我们举一个代码示例:
XML文件中的selector节点,我们举一个代码示例:
XML 文件保存在res/drawable/button.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/button_focused" />
<item android:drawable="@drawable/button_normal" /> <!-- default 默认-->
</selector>
item常用属性:
android:state_pressed 。“true”表示按下状态使用(例如按钮按下);“false”表示非按下状态使用。
android:state_focused 。“true”表示聚焦状态使用(例如使用滚动球/d-pad聚焦button);“false”表示非聚焦状态使用.
android:state_selected 。“true”表示选中状态使用(例如tab打开);“false”表示非选中状态使用。
android:state_checkable 。“true”表示可勾选状态时使用;“false”表示非可勾选状态使用。(只对能切换可勾选—非可勾选的构件有用。)
android:state_checked 。“true”表示勾选状态使用;“false”表示非勾选状态使用。
android:state_enabled 。“true”表示可用状态使用(能接收触摸/点击事件);“false”表示不可用状态使用。
android:window_focused 。“true”表示应用程序窗口有焦点时使用(应用程序在前台);“false”表示无焦点时使用(例如notification栏拉下或对话框显示)。
让这个XML用到一个Button上
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/button" />