一. 应用场景
日常开发中,我们会遇到一些Button、Textview…等控件的背景是圆角矩形、圆形…等,和android默认的控件背景矩形不一致,此时shape的作用就体现出来了,我们可以根据shape属性画出很多我们意想不到的背景图案。
具体使用方式:
1 2 3
|
android:background="@drawable/shape_radius"
|
二. Shape 标签
1. Shape标签的属性
常见的值:
还有更多的属性,用到了再更新。。。
2. Shape 下标签
① size 标签
1 2
| android:height:高度 android:width:宽度
|
注意事项:只有控件宽高设置成wrap_content时,此处宽高才起作用,但是起到的却是最小宽高值。也就是说,当控件宽高超过你此处指定的值时,它会变化。
② stroke 标签 — 设置边框相关
1 2 3 4
| android:color: 边框的颜色 android:width: 边框的宽度 android:dashWidth: 段虚线的宽度(可以将边界线理解成一段段线无间隔的连接) android:dashGap: 段虚线的间隔
|
③ corner 标签 — 设置边框圆角
1 2 3 4 5
| android:radius: 四个角圆角 android:topLeftRadius: 左上角的圆角 android:topRightRadius: 右上角的圆角 android:bottomLeftRadius: 左下角的圆角 android:bottomRightRadiusleft:右下角的圆角
|
注意:radius属性值可以被其他四个属性覆盖。
④ padding 标签 — 设置内间距
1 2 3 4
| android:left:左内边距 android:top:上内边距 android:right:右内边距 android:bottom:左内边距
|
⑤ soild 标签 — 设置填充颜色
三. 实例使用
1. 单独使用 Shape 标签
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke android:width="1dp" android:color="#44000000" />
<corners android:radius="5dp" />
</shape>
|

2. Selector嵌套不同状态的Shape
① 编辑框是否获得焦点的两种状态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="false"> <shape android:shape="rectangle"> <stroke android:width="2dp" android:color="#000000" />
<corners android:radius="5dp" />
<padding android:left="40dp" /> </shape> </item>
<item android:state_focused="true"> <shape android:shape="rectangle"> <stroke android:width="2dp" android:color="#00ff00" />
<corners android:radius="5dp" />
<padding android:left="40dp" /> </shape> </item>
</selector>
|


② 按钮是否可以使用的两种Shape
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false"> <shape android:shape="rectangle"> <corners android:radius="5dp" /> <solid android:color="#666666" /> </shape> </item>
<item android:state_enabled="true"> <shape android:shape="rectangle"> <corners android:radius="5dp" /> <solid android:color="#39A4F9" /> </shape> </item> </selector>
|


四. 补充内容
Android使用Shape实现阴影效果
参考文章
Android开发之Shape详细解读
详解shape标签