Android点击按钮切换背景效果-selector使用方法

有时候我们要实现“按下按钮和释放按钮时,按钮的背景图片(颜色)不同”的效果,我们可以用selector实现

1.编写XML代码:
在项目的res/drawable目录下新建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/button_pressed" /> <!--按下后的背景图片 -->
    <item android:drawable="@drawable/button_normal" /> <!-- 默认的背景图片  -->
</selector>
View Code


当然在该目录下要放入相关图片。

各属性解释:

android:state_pressed 是否按下,如一个按钮触摸或者点击。
android:state_focused 是否取得焦点,比如用户选择了一个文本框。
android:state_hovered 光标是否悬停,通常与focused state相同,它是4.0的新特性
android:state_selected 被选中,它与focus state并不完全一样,如一个list view 被选中的时候,它里面的各个子组件可能通过方向键,被选中了。
android:state_checkable 组件是否能被check。如:RadioButton是可以被check的。
android:state_checked 被checked了,如:一个RadioButton可以被check了。
android:state_enabled 能够接受触摸或者点击事件
android:state_activated 被激活android:state_window_focused 应用程序是否在前台,当有通知栏被拉下来或者一个对话框弹出的时候应用程序就不在前台了

2.在要设置此效果的Button的布局文件中添加:

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/button" />
原文地址:https://www.cnblogs.com/android-for-dh/p/4417856.html