android可以使用xml来绘制一些简单的图形,如渐变色、单色背景等。
1 使用xml绘制的好处
一般如果可以用xnl实现尽量不用图片资源实现。这样做的好处有几点:
1.1 使用灵活,想改就改
使用xml绘制的图片是使用代码实现的。所以要修改个颜色、修改个圆角什么的简单快捷。相反的,图片资源的修改必须找美工一遍遍的改。
1.2 节省资源空间
xml代码占用的空间要比图片小的多的多的多了,这是一个很好的优化android内存资源的方法。
2 xml的使用
2.1 使用layer-list实现带阴影的按钮背景
- <?xml version="1.0" encoding="utf-8"?>
- <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
- <!-- 阴影 -->
- <item>
- <shape android:shape="rectangle">
- <solid android:color="#33000000" />
- </shape>
- </item>
- <!-- 背景 -->
- <item android:bottom="3px">
- <shape android:shape="rectangle">
- <solid android:color="#FF13A4E0" />
- </shape>
- </item>
- </layer-list>
2.2 selection实现按钮点击效果
下面是使用shapre直接实现的按钮点击效果。
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_pressed="false">
- <shape android:shape="rectangle">
- <corners android:radius="3dp" />
- <solid android:color="#FFF3676A" />
- </shape>
- </item>
- <item android:state_pressed="true">
- <shape android:shape="rectangle">
- <corners android:radius="3dp" />
- <solid android:color="#FFEB373A" />
- </shape>
- </item>
- </selector>
2.3 shape的使用
填充
设置填充的颜色
间隔
设置四个方向上的间隔
大小
设置大小
圆角
android:Radius="20dp" 设置四个角的半径
android:topLeftRadius="20dp" 设置左上角的半径
android:topRightRadius="20dp" 设置右上角的半径
android:bottomLeftRadius="20dp" 设置右下角的半径
android:bottomRightRadius="20dp" 设置左下角的半径
描边
(dashWidth和dashGap两个属性中只要其中一个设置为0dp或者不设置,则边框为实现边框)
android:width="20dp" 设置边边的宽度
android:color="@android:color/black" 设置边边的颜色
android:dashWidth="2dp" 设置虚线长度
android:dashGap="20dp" 设置虚线间隔长度
- <?xml version="1.0" encoding="utf-8"?>
- <shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="rectangle">
- <!-- 图片圆角 -->
- <corners
- android:radius="9dp"
- android:topLeftRadius="2dp"
- android:topRightRadius="2dp"
- android:bottomLeftRadius="2dp"
- android:bottomRightRadius="2dp"/>
- <!-- 背景渐变 -->
- <gradient
- android:startColor="@android:color/white"
- android:centerColor="@android:color/black"
- android:endColor="@android:color/black"
- android:useLevel="true"
- android:angle="45"
- android:type="radial"
- android:centerX="0"
- android:centerY="0"
- android:gradientRadius="90"/>
- <!-- 间隔 -->
- <padding
- android:left="2dp"
- android:top="2dp"
- android:right="2dp"
- android:bottom="2dp"/><!-- 各方向的间隔 -->
- <!-- 大小 -->
- <size
- android:width="50dp"
- android:height="50dp"/><!-- 宽度和高度 -->
- <!-- 填充 -->
- <solid
- android:color="@android:color/white"/><!-- 填充的颜色 -->
- <!-- 描边 -->
- <stroke
- android:width="2dp"
- android:color="@android:color/black"
- android:dashWidth="1dp"
- android:dashGap="2dp"/>
- </shape>