有时候我们需要根据一个组件的不同状态来显示不同的图片,不如说一个按钮,就包含点击,聚焦,或者既不点击又不聚焦等状态,要使按钮在不同的状态下显示不同的样式或图片,这时就要用到selector,可以把组件的不同状态定义在一个xml文件中。
下面是一个实例:
EditText中随着文本框的状态来动态的改变输入的文字的颜色:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="@+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@drawable/editcolor"
/>
<EditText
android:id="@+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@drawable/editcolor"
/>
</LinearLayout>
Drawable文件夹下的editcolor.xml
<?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="#eee"
/>
上面定义了两个EditText,当光标处于第一个时,第二个中的文字是白色,第一个的文字是红色,当光标处于第二个时恰好相反。
也可以用两张不同的图片来表示按钮不同的状态的buttonback.xml,然后在Button中的androidbackground=”@drawable/buttonback”使用。