设置一个View,让其在按下和不按下显示不同的效果

     很多情况中,通过View来与应用程序进行交互,触摸手机屏幕时要发生变化。例如,有一个ImageView,默认的样子如下:  

1 

     当按下这个按钮时候,颜色加深,如下:

2

释放这个按钮以后,又恢复原来的颜色。

实现这种效果十分简单。

只需要在res/drawable文件下新建一个xml文件,名为mybutton.xml,假设上面的两个按钮对应的图片为button.png和button_down.png。xml文件为:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize="true">
    
    <!-- 背景色 -->
    <item android:state_enabled="true" android:state_pressed="false" 
        android:drawable="@drawable/button">
        
    </item>
    <!-- 手指放上时颜色 -->
    <item android:state_pressed="true" android:drawable="@drawable/button_down">    
    </item>
    
</selector>

以后要用这个效果的时候,只需在ImageView中加入:android:src="drawable/my_button"

原文地址:https://www.cnblogs.com/yangzhenyu/p/2167610.html