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

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

Android中的shape.xml怎么写 自定义圆角和边框-第1张图片-佛山资讯网

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

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~