控件自定义样式时,往往需要创建drawable文件实现。文件为xml格式,对于里面的结点
<shape>,<layer-list>
等进行学习
一、shape
用于形状图形的定义。格式如下.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="[rectangle|oval|line|ring]">
<corners />
<gradient />
<padding />
<size />
<solid />
<stroke />
</shape>
value | 定义 |
---|---|
rectangle | 矩形 |
oval | 椭圆形 |
line | 线性,需要<stroke> 定义线宽 |
ring | 环形 |
1.corner
为形状产生圆角,仅当形状为矩形时使用,属性设置如下
属性名 | 作用 |
---|---|
android:radius | 所有角的半径 ,会被下面的属性覆盖 |
android:topLeft(right)Radius | 左(右)上角的半径 |
android:bottomLeft(right)Radius | 左(右)下角的半径 |
2.gradient
指定形状的渐变颜色。使用该属性时不要使用solid,会被覆盖
属性名 | 作用 |
---|---|
android:angle | 渐变的角度,默认为0。必须为45的倍数。0为从左到右, 90为从上到下。 |
android:centerX(Y) | 浮点值0-1.0。渐变中心相对X轴(Y轴)的位置 |
android:centerColor | 起始颜色与结束颜色之间的可选颜色 |
android:start(end)Color | 开始结束颜色 |
android:type | 要应用的渐变图案的类型。linear线性渐变,radial径向渐变,sweep流线型渐变 |
android:gradientRadius | 渐变的半径,仅在type为radial时使用,则radial必须有该属性 |
3.padding
定义内部边距
android:left,right,top,bottom
4.size
定义形状的大小。形状按照定义的尺寸按比例缩放至容器试图的大小。
5.solid
定义填充形状的颜色
6.stroke
定义描边属性,描边的宽度颜色虚实线等
属性名 | |
---|---|
android:width | 描边线宽 |
android:color | 描边颜色 |
android:dashWidth | 描边虚线每个短划线的长度 |
android:dashGap | 描边虚线的间距 |
二、layer-list
图层列表,大致原理是一层层叠加,后添加的会覆盖先添加的。可通过控制后面的添加图层距离最底层图层的上下左右四个边距属性,得到不同的显示效果,如指定边边框、阴影等。
不同的图层用<item>
节点来定义
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item> <!--底部蓝色填充-->
<shape>
<solid android:color="#02a0ef"/>
</shape>
</item>
<!--该层距离底层顶部1dp 底部1dp,就完成了顶部底部蓝色线条的效果-->
<item android:bottom="1dp"
android:top="1dp">
<shape>
</shape>
</item>
</layer-list>
三、selector
选择器,根据控件的不同状态显示不同的背景
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item />
<item android:state_.....>
<layer-list>
<item>
<shape>
</selector>