android button背景随心搭配

本文介绍如何使用selector和layer-list实现按钮背景的层叠组合,通过不同的状态(如按下、正常)展示不同的视觉效果。具体包括利用XML定义背景颜色渐变、添加前景图片等步骤。

这里我举例如何使用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是一张前景图片,即按下时的顶部阴影:2011012211330582.png

至此,已完成高亮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处理类似高亮,不贴代码了

 

下面是运行效果截图:

普通2011012211505115.png  高亮2011012211510895.png

 

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

转载于:https://www.cnblogs.com/nicklezhang/archive/2011/01/22/1941911.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值