初学Android,使用Drawable资源之使用StateListDrawable资源(十三) .

StateListDrawable用于组织多个Drawable对象,顾名思义,StateList,它会随着目标组件状态(比如得到/失去焦点,勾选/未勾选,可用/不可用,按下/未按下,等等)的改变而自动切换

StateListDrawable对象的XML文件的根元素是<selector.../>,可包含多个<item.../>元素

下面是一个高亮显示正在输入的文本框的例子

创建一个普通Android xml文件,根元素选择selector,文件名为my_image,创建完以后把文件移动到res/drawable-mdpi文件夹下

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:state_focused = "true"  
  4.           android:color = "#f44"   
  5.     />  
  6.     <item android:state_focused = "false"  
  7.           android:color = "#111"   
  8.     />  
  9. </selector>  
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused = "true"
          android:color = "#f44" 
    />
    <item android:state_focused = "false"
          android:color = "#111" 
    />
</selector>

下面的主界面xml中引用上面定义的样式

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <EditText  
  8.         android:id="@+id/editText1"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:textColor="@drawable/my_image"  
  12.         android:ems="10"  />  
  13.   
  14.   
  15.     <EditText  
  16.         android:id="@+id/editText2"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:textColor="@drawable/my_image"  
  20.         android:ems="10" />  
  21.   
  22. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/my_image"
        android:ems="10"  />


    <EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/my_image"
        android:ems="10" />

</LinearLayout>


效果如下,当焦点在文本框时,文字变为高亮显示


扫描二维码关注公众号,回复: 842722 查看本文章

猜你喜欢

转载自chenqiang5206.iteye.com/blog/1628941