Android 资源简介(一) StateListDrawable

StateListDrawable 用于组织多个 Drawable 对象。当使用 StateListDrawable 作为目标组件的背景、前景图片时,StateListDrawable 对象所显示的 Drawable 对象会随目标组件的状态的改变而自动切换。

定义 StateListDrawable 对象的 XML 文件的根元素为 <selector>,该元素可以包含多个 <item> 元素,该元素可以指定如下属性:

  1. android:color 或 android:drawable:指定颜色或 Drawable 对象;
  2. android:state_xxx:指定的状态。

StateListDrawable 的 <item> 元素所支持的状态如下所示:

属性值含义
android:state_active是否激活
android:state_checkable是否可勾选
android:state_checked是否已勾选
android:state_enabled是否可用
android:state_first是否处于开始状态
android:state_focused是否已获得焦点
android:state_last是否处于结束状态
android:state_middle是否处于中间状态
android:state_pressed是否按下
android:state_selected是否选中
android:state_window_focused是否窗口已获得焦点

下面是一个简单的使用示例:

自定义的 drawable 文件 my_image.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" />
</selector>

布局文件的内容:

<?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:background="@color/colorGray"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/my_image"
        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColor="@drawable/my_image"
        />

</LinearLayout>

主程序文件的内容如下:

package com.toby.personal.testlistview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    final private static String TAG = "Toby_Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

程序的运行效果:

《Android 资源简介(一) StateListDrawable》 运行效果

参考文献:《疯狂Android讲义(第2版)》

    原文作者:赵者也
    原文地址: https://www.jianshu.com/p/ac0a1def06b3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞