官方文档:
Lets you assign a number of graphic images to a single Drawable and swap out the visible item by a string ID value.
It can be defined in an XML file with the <selector>
element. Each state Drawable is defined in a nested <item>
element. For more information, see the guide toDrawable Resources.
StateListDrawable类定义了不同状态下,与之对应的资源(更多时候是图片资源)。
StateListDrawable可以在xml文件中定义,通过<selector>标签。其中每个状态的属性(可以是设置drawable,图片资源),可以通过<item>元素来设置。
下面写的例子不是状态与图片的切换,只是简单的在状态改变时,改变字体的颜色属性。
关于StateListDrawable的详细解析,可参考Android中View(视图)绘制不同状态背景图片原理深入分析以及StateListDrawable使用详解
开始贴出小例子:
在focus.xml文件中定义StateListDrawable,设置的item主要是控制焦点获得/失去时,颜色的变化。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 设置控件属性,是否获得焦点 cause 显示不同颜色 -->
<item android:state_focused="true" android:color="#f44"/>
<item android:state_focused="false" android:color="#111"/>
</selector>
在布局文件main.xml中添加了两个EditText控件,将控件中默认字体颜色设置成focus.xml文件中控制的属性颜色。
<?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" >
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<!-- android:textColor属性使用了focus.xml文件中定义的颜色 -->
<EditText
android:id="@+id/edit01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StateListDrawable"
android:textColor="@drawable/focus" />
<EditText
android:id="@+id/edit02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StateListDrawable"
android:textColor="@drawable/focus" />
</LinearLayout>
主Activity中没有添加什么语句,这样运行,就可以看到以下效果图:
上面一个EditText获得焦点时
下面一个EditText获得焦点时