android button背景随心搭配

里我举例如何使用selector,layer-list完成button背景的层叠组合,从而有不同情形下不同效果

button_ctrl.xml中选择器

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable
="@drawable/button_highlight_ctrl" />
<item android:drawable="@drawable/button_normal_ctrl" />
</selector>

button_highlight_ctrl.xml中两层图

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/button_highlight_back"
android:top
="2dip"
android:right
="2dip"
android:bottom
="2dip"
android:left
="2dip"/>
<item
android:drawable="@drawable/button_highlight_fore"
android:top
="2dip"
android:right
="2dip"
android:bottom
="2dip"
android:left
="2dip"/>
</layer-list>
button_highlight_back.xml中完成背景颜色的渐变

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape
="rectangle">
<corners
android:radius="4dip"/>
<gradient
android:type="linear"
android:angle
="270"
android:startColor
="@color/highlight_button_start_color"
android:centerColor
="@color/highlight_button_middle_color"
android:endColor
="@color/highlight_button_end_color"/>
</shape>
button_highlight_fore是一张前景图片,即按下时的顶部阴影:

至此,已完成高亮button的制作,接下来是普通button

button_normal_ctrl.xml中两层图

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/button_normal_back"
android:top
="2dip"
android:right
="2dip"
android:bottom
="2dip"
android:left
="2dip"/>
<item
android:drawable="@drawable/button_normal_fore"
android:top
="2dip"
android:right
="2dip"
android:bottom
="1dip"
android:left
="2dip"/>
</layer-list>
button_normal_back.xml和button_normal_fore处理类似高亮,不贴代码了

 

下面是运行效果截图:

普通  高亮

 

当然前面不一定写字符,可以是一张图片。总之变化可以多样,核心思想是一致的。

posted @ 2011-05-22 20:57  jacktu  阅读(1290)  评论(0编辑  收藏  举报