美文网首页Android 成长笔记
Android 资源简介(一) StateListDrawabl

Android 资源简介(一) StateListDrawabl

作者: 赵者也 | 来源:发表于2017-04-05 16:48 被阅读67次

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讲义(第2版)》

相关文章

网友评论

    本文标题:Android 资源简介(一) StateListDrawabl

    本文链接:https://www.haomeiwen.com/subject/csztattx.html