自定义Button,主要是对背景android:background 进行自定义。background 属性可以指定一个颜色的RGB值,也可以指定一个drawable 对象,一般为shape drawable 或者state-list drawable。
先来研究一下系统主题下的Button 样式。
打开styles.xml,找到系统下的Button 样式如下:
<style name="Widget.Button">
<item name="background">@drawable/btn_default</item>
<item name="focusable">true</item>
<item name="clickable">true</item>
<item name="textAppearance">?attr/textAppearanceSmallInverse</item>
<item name="textColor">@color/primary_text_light</item>
<item name="gravity">center_vertical|center_horizontal</item>
</style>
主要看一下background 属性。打开btn_default.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true"
android:drawable="@drawable/btn_default_normal" />
<item android:state_window_focused="false" android:state_enabled="false"
android:drawable="@drawable/btn_default_normal_disable" />
<item android:state_pressed="true"
android:drawable="@drawable/btn_default_pressed" />
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/btn_default_selected" />
<item android:state_enabled="true"
android:drawable="@drawable/btn_default_normal" />
<item android:state_focused="true"
android:drawable="@drawable/btn_default_normal_disable_focused" />
<item
android:drawable="@drawable/btn_default_normal_disable" />
</selector>
发现Button 的主要样式都定义在这里了。
根元素用<selector>指定,说明这是一个state list drawable。在根元素下有许多<item>子元素对象,每个item 都可以指定不同状态下的样式。android:state_XXX 用于指定样式,android:drawable 用于指定该样式下应用的背景。对于Button 来说,就有pressed, enabled 等多种状态。
再随便打开一个item 下的drawable,就可以看到这个Button 到底长什么样了。
关于打开的方法,可以直接用Ctrl+鼠标左键,如果这样不行的话,可以直接到sdk的目录下查找,例如:
可以看到,系统中直接用一张 .9 的文件来定义按键的背景。
明白了这些以后,其实自定义Button 很简单,只需要将background 替换成自己的drawable :
android:background="@drawable/btn_login"
首先在drawable 文件夹下新建一个xml文件,根元素为<selector>:
btn_login.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_login_normal" android:state_pressed="false"/>
<item android:drawable="@drawable/btn_login_pressed" android:state_pressed="true"/>
</selector>
这里只指定了正常和按下两种状态,如果有需要,也可以指定其他状态。drawable 属性可以是一张图片,也可以是shape drawable 的对象,例如:
btn_login_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ff0000cc" />
<corners android:radius="5dp" />
</shape>
在上面的代码中,<solid>指定了颜色,<corners>指定了圆角。也可以使用<gradient>指定渐变颜色,<stroke>指定边框等等。。。