016 Android 图片选择器(在选中和未选中的过程中,切换展示图片)

1.目标效果

在选中和未选中的过程中,切换展示图片

2.实现方法

(1)在app--->res--->drawable

右击drawable文件夹右键,new ---->drawable resource file

注意:生成的xml文件必须在drawable目录下,而不是在drawable(v24)包下。

(2)编写xml文件

实例:selector_nextbtn_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--选中用深绿色的图-->
    <item android:state_pressed="true" android:drawable="@drawable/function_greenbutton_pressed"></item>
    <!--未选中用浅绿色的图-->
    <item android:drawable="@drawable/function_greenbutton_normal"></item>
</selector>

(3)图片选择器的使用

往往通过设置控件的 android:background 属性。

<Button
            android:text="下一页"
            android:background="@drawable/selector_nextbtn_bg"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

3.效果图

观察按钮颜色的变化。

参考文献:https://developer.android.google.cn/guide/topics/resources/drawable-resource#StateList

原文地址:https://www.cnblogs.com/luckyplj/p/10820001.html