android drawable
概述
凡是要在屏幕上绘制的东西都可以叫drawable
shape drawable
使用shape drawable可以绘制圆形、长方形、梯形、线条等,XML drawable和屏幕像素密度无关,所以无需考虑创建特定像素密度目录,直接放入drawable文件夹就可以了
定义shape
button_beat_box_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"> <!-- 定义一个圆 -->
<solid
android:color="@color/dark_blue"/> <!-- 背景为深蓝色的圆形-->
</shape>
button_beat_box_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/red" />
</shape>
在样式中使用
<style name="BeatBoxButton" parent="Widget.AppCompat.Button">
<item name="android:background">@drawable/button_beat_box_normal</item>
</style>
state list drawable
state list drawable 支持 按下、禁用、聚焦、激活等状态
创建state list drawable
button_beat_box.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_beat_box_pressed" android:state_pressed="true" /> <!--按下时-->
<item android:drawable="@drawable/button_beat_box_normal" /> <!--正常时-->
</selector>
使用
<style name="BeatBoxButton" parent="Widget.AppCompat.Button">
<item name="android:background">@drawable/button_beat_box</item>
</style>
layer list drawable
layer list drawable 能让多个drawable合而为一,
实例
定义一个红圈定,再义一个4dp粗粗的深红圈,这会产生一个暗红圈
定义
button_beat_box_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/red" />
</shape>
</item>
<item>
<shape android:shape="oval">
<stroke
android:width="4dp"
android:color="@color/dark_red"/>
</shape>
</item>
</layer-list>
使用
<style name="BeatBoxButton" parent="Widget.AppCompat.Button">
<item name="android:background">@drawable/button_beat_box</item>
</style>