在Android开发中, 扁平化按钮已常见不鲜, 得空也琢磨了一下,也并不复杂,应付日常开发,这些也够用了.
首先,在drawable中建两个.xml文件,normal.xml与pressed.xml
常见的Attributes字段:
android:state_pressed Boolean “true”表示按下状态使用;“false” 表示非按下状态使用。
android:state_focused Boolean “true”表示聚焦状态使用(例如使用滚动球/D-pad聚焦Button);“false”表示非聚焦状态使用。
android:state_selected Boolean “true”表示选中状态使用(例如Tab 打开);“false”表示非选中状态使用。
android:state_checkable Boolean “true”表示可勾选状态时使用;“false”表示非可勾选状态使用。(只对能切换可勾选—非可勾选的构件有用。)
android:state_checked Boolean “true”表示勾选状态使用;“false”表示非勾选状态使用。
android:state_enabled Boolean “true”表示可用状态使用(能接收触摸/点击事件);“false”表示不可用状态使用。
android:window_focused Boolean “true”表示应用程序窗口有焦点时使用(应用程序在前台);“false”表示无焦点时使用(例如Notification栏拉下或对话框)
在xml文件中 layer-list下shape有几个主要的 Attributes字段,需注意:
(1)solid:填充颜色
(2)corners:圆角幅度
(3)stroke:设置周边 width:边框宽度 color:边框颜色
(4)gradient:设置渐变色
(5)padding:内边距
bg01_normal:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<corners android:radius="8dp" />
<solid android:color="@color/burlywood" />
</shape>
</item>
<item android:bottom="4dp">
<shape android:shape="rectangle" >
<gradient android:startColor="#FF2f4f4f" android:centerColor="#AA2f4f4f"
android:endColor="#882f4f4f" />
<corners android:radius="8dp" />
</shape>
</item>
</layer-list>
bg01_pressed:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<corners android:radius="8dp" />
<solid android:color="#00000000" />
</shape>
</item>
<item android:top="4dp">
<shape android:shape="rectangle">
<corners android:radius="8dp"/>
<gradient android:startColor="#FF2f4f4f" android:centerColor="#AA2f4f4f"
android:endColor="#882f4f4f" />
</shape>
</item>
</layer-list>
bg01_selector:
<?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_bg01_pressed"></item>
<item android:drawable="@drawable/button_bg01_normal"></item>
</selector>
最后设置按钮的background即可: