Android中的selector

在drawable/xxx.xml中配置,通过配置selector,可以使系统运行时根据控件对象的状态使用相应的图片、文字等。

  • android:state_selected 控件选中状态,可以为true或false
  • android:state_focused 控件获得焦点状态,可以为true或false
  • android:state_pressed 控件点击状态,可以为true或false
  • android:state_enabled 控件使能状态,可以为true或false
  • android:state_checkable 控件可勾选状态,可以为true或false
  • android:state_checked 控件勾选状态,可以为true或false

注意:在状态描述中,第一个匹配当前状态的item会被使用。因此,如果第一个item没有任何状态特性的话,那么它将每次都被使用,所以默认的值必须总是在最后。

  • android:window_focused 应用程序窗口焦点状态,可以为true或false
  • android:color 定义特定状态的颜色为16进制颜色。这个颜色由rgb值指定,可带alpha,必须以”#“开头,后面跟随alpha-red-green-blue信息,格式可以为:#rgb,#argb,#rrggbb,#aarrggbb

例子01:

<?xml version="1.0" encoding="utf-8" ?>   
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- 默认时的背景图片 -->  
  <item android:drawable="@drawable/pic1" />
 
  <!-- 没有焦点时的背景图片 -->  
  <item android:state_window_focused="false" 
        android:drawable="@drawable/pic1" />   
 
  <!-- 非触摸模式下获得焦点并单击时的背景图片 -->  
  <item android:state_focused="true" android:state_pressed="true"   
        android:drawable= "@drawable/pic2" />  
 
  <!-- 触摸模式下单击时的背景图片 -->  
  <item android:state_focused="false" android:state_pressed="true"   
        android:drawable="@drawable/pic3" />   
 
  <!--选中时的图片背景  -->  
  <item android:state_selected="true"   
        android:drawable="@drawable/pic4" />   
 
  <!--获得焦点时的图片背景  -->  
  <item android:state_focused="true"   
        android:drawable="@drawable/pic5" />   
</selector>

例子02:

按下或获取焦点时让button呈现不同的状态

<?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/login_button2" /> 
    <item android:state_focused="true" 
        android:drawable="@drawable/login_button2" /> 
    <item android:drawable="@drawable/login_button" /> 
</selector> 

使用方式:

   <Button
        android:id="@+id/style_button_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="16dp"
        android:text="用代码动态设定点击样式" />

参考自:

http://blog.csdn.net/breeze666/article/details/7747649

http://www.cnblogs.com/tianzhijiexian/p/3854962.html

原文地址:https://www.cnblogs.com/tianzhijiexian/p/4296647.html