在Android应用中,绝大部分情况下,按钮都有按下变色的效果,这种效果主要都是借助于Android里面的 StateListDrawable来实现的,它可以设置多种状态,并分别为每种状态设置相应的drawable,这个drawable有两种方式来实现:1、准备多张图片 2、准备多个 ShapeDrawable。下面用第二种方式来实现一下按钮变色的效果。
1、btn_shape.xml
,正常状态下的背景图
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="5dp" /> <solid android:color="@color/material_green" /> </shape>
2、btn_shape_press.xml
,按下状态下的背景图
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="5dp" /> <solid android:color="@color/material_dark_green" /> </shape>
其中,corners:圆角度数, solid:填充色
btn_shape_press.xml
<?xml version="1.0" encoding="utf-8" ?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 触摸模式下单击时的背景图片--> <item android:drawable="@drawable/btn_shape_press" android:state_pressed="true" /> <!-- 默认时的背景图片--> <item android:drawable="@drawable/btn_shape" /> </selector>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="20dp" android:background="@drawable/btn_selector" android:text="请按我,给你点颜色看看" android:textColor="@color/white"></Button> </RelativeLayout>
按钮点击变色.gif
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句