在Android开发中,shape.xml作为drawable资源的一种,能够通过XML配置直接生成图形,常被用来实现控件的圆角、边框等样式,不需要额外引入图片资源,适配性更好。

shape.xml的基础结构
shape.xml的根标签是<shape>,需要指定命名空间,并且通过android:shape属性定义图形类型,可选值有rectangle(矩形,默认)、oval(椭圆)、line(线)、ring(环形)。实现圆角和边框通常使用默认的矩形类型即可。
基础结构示例如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 这里添加子标签配置样式 -->
</shape>
自定义圆角的实现方法
圆角通过<corners>标签配置,该标签支持设置四个角统一圆角,也可以单独设置每个角的圆角大小。
常用属性说明:
android:radius:统一设置四个角的圆角半径,优先级低于单独设置的角属性android:topLeftRadius:设置左上角圆角半径android:topRightRadius:设置右上角圆角半径android:bottomLeftRadius:设置左下角圆角半径android:bottomRightRadius:设置右下角圆角半径
实现统一圆角8dp的示例:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
</shape>
实现左上角和右上角为8dp,左下角和右下角为0dp的示例:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:topLeftRadius="8dp"
android:topRightRadius="8dp"
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp" />
</shape>
自定义边框的实现方法
边框通过<stroke>标签配置,可设置边框的宽度、颜色、虚线样式等。
常用属性说明:
| 属性名 | 作用 |
|---|---|
| android:width | 设置边框的宽度 |
| android:color | 设置边框的颜色 |
| android:dashWidth | 设置虚线的线段长度,不设置则为实线 |
| android:dashGap | 设置虚线的线段间隔,需要和dashWidth配合使用 |
实现2dp宽度、黑色实线边框的示例:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#FF000000" />
</shape>
实现3dp宽度、红色虚线边框的示例:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="3dp"
android:color="#FFFF0000"
android:dashWidth="5dp"
android:dashGap="3dp" />
</shape>
同时设置圆角和边框的完整示例
实际开发中通常需要同时设置圆角和边框,还可以搭配<solid>标签设置填充颜色,<padding>标签设置内部间距。
下面是一个同时包含圆角、边框、填充色、内间距的完整示例:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 设置圆角 -->
<corners android:radius="10dp" />
<!-- 设置边框 -->
<stroke
android:width="2dp"
android:color="#FF6200EE" />
<!-- 设置填充颜色 -->
<solid android:color="#FFFFFFFF" />
<!-- 设置内间距 -->
<padding
android:left="12dp"
android:top="8dp"
android:right="12dp"
android:bottom="8dp" />
</shape>
将上述文件保存为res/drawable/shape_custom.xml后,就可以在布局文件中作为控件的背景使用:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义圆角边框样式"
android:background="@drawable/shape_custom" />
注意事项
- 如果同时设置了
android:radius和单独角的圆角属性,单独角的属性会生效 - 边框的宽度如果设置过大,可能会覆盖部分控件内容,需要合理调整宽度值
- 虚线边框在硬件加速开启的情况下可能无法正常显示,此时可以在对应Activity中关闭硬件加速,或者改用其他方式实现