在界面开发设计过程中,我们经常有按钮点击前与点击后的效果,这个时候,就必须使用selector了,而有时候,美工偷懒不给你设计按钮图片背景的时候,那么我们就需要自己使用shape来画了,shape支持画矩形和椭圆,圆形。所以这两项技术,我们是经常需要使用的。selector和shape设计的xml,我们都放在drawable文件夹下的。
好的,这里给出一个简单的用法。
第一步:设计selector_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--方法一:采用drawable,item状态有很多android:state_checked,state_pressed等等,自己按需选择-->
<!--点击状态下-->
<item android:drawable="@mipmap/btn_camera_take_picture_small_b" android:state_pressed="true"></item>
<!--没写状态表示常态写-->
<item android:drawable="@mipmap/btn_camera_take_picture_small_a"></item>
<!--方法二:采用shape,shape里面不是所有的属性都需要的,自己按需选选择,另外shape也可以单独自己创建一个xml文件放在drawable文件夹下-->
<!--点击状态下-->
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="#cdcdcd" />
<corners android:radius="2dp" />
</shape>
</item>
<!--没写状态表示常态写-->
<item>
<shape android:shape="rectangle">
<!--大小-->
<size android:width="100dp" android:height="100dp"></size>
<!-- 顏色填充 -->
<solid android:color="#587df9" />
<!-- 圆角 还可以单独设置四个圆角的圆半径,比如topLeftRadius左上圆角半径-->
<corners android:radius="2dp" />
<!-- 渐变 -->
<gradient android:angle="270" android:endColor="#FFFFFF" android:startColor="#ff8c00" />
<!-- 描边 -->
<stroke android:width="2dp" android:color="#dcdcdc" />
<!--上下左右padding-->
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
</shape>
</item>
</selector>
第二步:Button或者其他View使用selector_button.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_button"
android:text="购买" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/selector_button"/>