StateListDrawable资源的使用

StateListDrawable用于组织多个Drawable对象,当使用StateListDrawable作为目标组件的 背景和前景图片时,StateListDrawable对象所显示的Drawable对象会随着目标组件状态的改变而改变, 说白了就是给某个组件添加颜色选择器, 比如一个按钮 按下和离开状态会有不同颜色

StateListDrawable支持的状态如下

举一个例子, 当EditText获取焦点时,显示红色, 失去焦点时显示默认黑色

在res/drawable/创建myImage.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="#111"
    />
</selector>

布局文件EditText引入

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

获取焦点和失去焦点效果如下

如果想做某些按钮或者GridView等等的点击效果,参考上面图标提供参数即可实现

原文地址:https://www.cnblogs.com/android-zcq/p/3147396.html