在Android应用的开发过程中,我们经常要根据控件的状态,改变控件的显示,比如EditeText在focus,或者是unfocus时设置背景颜色的不同,这个相信大家在以前肯定看到过,通过Selector就可以实现,但是如何让EditeText在focus,或者是unfocus时设置不同的颜色呢?接下来说的ColorStateList就是这样的功能。
新建一个项目,为了便于观察,在默认的main.xml文件里面拖入两个EditeText,然后在drawable文件夹中新建一个color_stat_list.xml,在里面输入以下内容:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="#FF0000" android:state_focused="true" ></item>
<item android:color="#00FF00" android:state_focused="false" ></item>
</selector>
编辑EditText,设置它们的android:textColor="@drawable/color_state_list",形如:
<EditText
android:id="@+id/editText1"
android:textColor="@drawable/color_state_list"
android:text="@string/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
<EditText
android:id="@+id/editText1"
android:textColor="@drawable/color_state_list"
android:text="@string/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
保存项目,然后运行。效果如下图所示: