Android中的shape.xml怎么写 自定义圆角和边框

4次阅读

android中shape.xml是定义Drawable资源的XML文件,用于实现圆角、边框、渐变等效果;根元素为,需指定android:shape类型(如rectangle、oval等);rectangle支持设圆角,设边框,设填充色;常存于res/drawable/下,通过@drawable引用。

Android中的shape.xml怎么写 自定义圆角和边框

Android 中的 shape.xml 是用 XML 定义的 Drawable 资源,常用于实现按钮、背景等的圆角、边框、渐变等效果。它写在 res/drawable/ 目录下,通过 android:background="@drawable/xxx" 引用。

基础结构:必须的根标签和 shape 类型

所有 shape 必须以 <shape></shape> 为根节点,并指定 android:shape 类型,常用值有:

  • rectangle(矩形,最常用,支持圆角、边框、填充)
  • oval(椭圆,可用于圆形按钮或进度条背景)
  • line(直线,需配合 <stroke></stroke> 使用)
  • ring(环形,多用于 ProgressBar)

实现圆角:用 corners 标签控制四个角

只有 android:shape="rectangle" 支持 <corners></corners>。可统一设圆角半径,也可单独设置每个角:

<corners     android:radius="8dp"           <!-- 四个角统一圆角 -->     android:topLeftRadius="4dp"     android:topRightRadius="12dp"     android:bottomLeftRadius="0dp"     android:bottomRightRadius="8dp" />

注意:android:radius 会覆盖各方向独立属性;若只设某几个角,其余默认为 0。

添加边框:用 stroke 标签定义线条

<stroke></stroke> 用来画边框,支持颜色、宽度、虚线(可选):

<stroke     android:width="2dp"     android:color="#FF6B6B"     android:dashWidth="6dp"      <!-- 虚线每段长度 -->     android:dashGap="4dp"        <!-- 虚线间隔 --> />

⚠️ 如果只加边框不设填充(<solid></solid>),默认是透明背景,看起来就像“空心”矩形。需要边框+背景色时,记得同时加 <solid android:color="#F5F5F5"></solid>

Android中的shape.xml怎么写 自定义圆角和边框

美图AI开放平台

美图推出的AI人脸图像处理平台

Android中的shape.xml怎么写 自定义圆角和边框 111

查看详情 Android中的shape.xml怎么写 自定义圆角和边框

完整示例:带圆角、边框和背景色的按钮背景

保存为 res/drawable/bg_rounded_button.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle"> <pre class="brush:php;toolbar:false;"><solid android:color="#E0F7FA" />     <!-- 背景色 --> <corners android:radius="10dp" />       <!-- 整体圆角 --> <stroke     android:width="2dp"     android:color="#00ACC1" />          <!-- 边框色和粗细 -->

然后在 Button 中使用:android:background="@drawable/bg_rounded_button"

基本上就这些。shape.xml 不复杂但容易忽略细节,比如漏写 <solid></solid> 导致背景透明,或误用 oval 却想设 corners(不支持)。按需组合 corners、stroke、solid 就能覆盖大多数 ui 场景。

text=ZqhQzanResources