由于Button控件的聚焦和点击时的背景实在难看,所以很多时候我们都要为Button指定新的背景色,这里我们通过selector的方式去设置,首先看一下怎样写drawable,如下面的日志:http://www.cnblogs.com/cyanfei/archive/2012/07/27/2612023.html ,这篇日志很好地总结了怎样自定义drawable。
现在写一个selector,在res目录下新建一个目录drawable,在这个新的目录下新建一个xml文件,名字随意,这里取名button_selector.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false">
<shape >
<solid android:color="#ffc2b7"/>
</shape>
</item>
<item android:state_focused="true">
<shape >
<solid android:color="#ff91c3"/>
</shape>
</item>
</selector>
可以看到,selector标签中有两个item标签,分别指定button空间聚焦和非聚焦状态下的背景,这里也可以指定更多状态,如点击事件。
在Layout文件中可以这样来指定button的selector
<Button
android:id="@+id/but_no"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/but_yes"
android:layout_alignTop="@id/but_yes"
android:layout_marginLeft="100dp"
android:background="@drawable/but_selector"
android:textSize="25sp"
android:text="@string/no" />