StateListDrawable、ColorStateList

知识点一:StateListDrawable类介绍

 

类功能说明:该类定义了不同状态值下与之对应的图片资源,即我们可以利用该类保存多种状态值,多种图片资源。

常用方法为:

public void addState (int[] stateSet, Drawable drawable)

功能: 给特定的状态集合设置drawable图片资源

使用方式:参考前面的hello_selection.xml文件,我们利用代码去构建一个相同的StateListDrawable类对象。

//初始化一个空对象
StateListDrawable stalistDrawable = new StateListDrawable();
//获取对应的属性值 Android框架自带的属性 attr
int pressed = android.R.attr.state_pressed;
int window_focused = android.R.attr.state_window_focused;
int focused = android.R.attr.state_focused;
int selected = android.R.attr.state_selected;
stalistDrawable.addState(newint []{pressed , window_focused}, getResources().getDrawable(R.drawable.pic1));
stalistDrawable.addState(newint []{pressed , -focused}, getResources().getDrawable(R.drawable.pic2);
stalistDrawable.addState(newint []{selected }, getResources().getDrawable(R.drawable.pic3);
stalistDrawable.addState(newint []{focused }, getResources().getDrawable(R.drawable.pic4);
//没有任何状态时显示的图片,我们给它设置我空集合
stalistDrawable.addState(newint []{}, getResources().getDrawable(R.drawable.pic5);

上面的“-”负号表示对应的属性值为false

当我们为某个View使用其作为背景色时,会根据状态进行背景图的转换。

public boolean isStateful ()

功能: 表明该状态改变了,对应的drawable图片是否会改变。

注:在StateListDrawable类中,该方法返回为true,显然状态改变后,我们的图片会跟着改变。

 

 

在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>

 

 

原文地址:https://www.cnblogs.com/zhouchanwen/p/2735673.html