忙了一段时间,终于有时间整理整理之前所用到的一些知识,分享给大家,希望给同学们有些帮助,同时也是对自己的知识有个巩固的过程。
在Android的开发中比较常用的控件就是Button了,但是我们平时使用Button时是怎样来设置按下和抬起显示不同的效果呢?我想一般的实现方式就是定义一个selector的xml文件,然后在里面根据不同的state来设置不同的图片,但是当Button控件非常多的时候,就要写对应数量的xml文件,导致大码非常臃肿。
今天我们换种方式来改变这个样式,只需要两行代码即可实现按下的效果,同时支持圆角和圆形的按钮的样式。先看下效果图,这是我写的一个demo
接下来讲一下主要代码:
第一步 自定义属性
在res/values/目录下新建attrs.xml文件,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--公共属性-->
<attr name="backColor" format="color" />
<attr name="backColorPress" format="color" />
<attr name="backGroundImage" format="reference" />
<attr name="backGroundImagePress" format="reference" />
<attr name="textColor" format="color" />
<attr name="textColorPress" format="color" />
<declare-styleable name="buttonM">
<attr name="backColor" />
<attr name="backColorPress" />
<attr name="backGroundImage" />
<attr name="backGroundImagePress" />
<attr name="textColor" />
<attr name="textColorPress" />
<attr name="fillet" format="boolean" />
<attr name="radius" format="float" />
<attr name="shape">
<enum name="rectangle" value="0" />
<enum name="oval" value="1" />
<enum name="line" value="2"