Android的attrs.xml文件怎么写 自定义View属性教程

attrs.xml 是 Android 中定义自定义 View 属性的核心文件,需在 res/values/ 下创建,用 声明属性组,配合 指定 name 和 format 类型,在布局中通过 xmlns:app 和 app:xxx 使用,并在 View 构造函数中通过 TypedArray 读取,务必调用 recycle()。

Android 的 attrs.xml 是定义自定义 View 属性的核心文件,它让控件支持在 XML 布局中通过自定义属性配置行为或样式。写对它,才能让自定义 View 真正“可配置、可复用、可维护”。

1. 创建 attrs.xml 文件

res/values/ 目录下新建一个 XML 文件,命名为 attrs.xml(名字可自定义,但推荐统一叫这个)。文件根节点必须是

示例:



  

2. 定义自定义属性(declare-styleable)

包裹一组相关属性,name 通常与自定义 View 类名一致(便于识别和 IDE 提示)。

每个属性用 声明,需指定 name 和 format(类型)。

常用 format 类型包括:

  • reference:引用资源(如 @drawable/xxx、@color/xxx)
  • color:颜色值(#RGB、#ARGB、@color/xxx)
  • dimension:尺寸(16dp、24sp、@dimen/xxx)
  • string:字符串(支持 @string/xxx)
  • boolean:布尔值(true/false)
  • integer:整数
  • enum:枚举(需配合 子标签)
  • flag:位运算标志(类似 enum,但支持多选)

示例:为一个圆形进度条定义属性


  
  
  
  
  
  
  
  

3. 在布局 XML 中使用自定义属性

先在布局根标签中声明命名空间(推荐用 app):

xmlns:app="http://schemas.android.com/apk/res-auto"

然后在自定义 View 标签中使用 app:xxx 引用属性:

  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:cpv_max="100"
  app:cpv_progress="65"
  app:cpv_stroke_width="8dp"
  app:cpv_stroke_color="@color/blue"
  app:cpv_show_text="true" />

4. 在自定义 View 构造函数中读取属性

在自定义 View 的三个构造函数中(尤其带 AttributeSet 的那个),用 TypedArray 获取属性值:

public CircleProgressView(Context context, AttributeSet attrs) {
  super(context, attrs);
  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressView);
  max = a.getInt(R.styleable.CircleProgressView_cpv_max, 100);
  progress = a.getInt(R.styleable.CircleProgressView_cpv_progress, 0);
  strokeWidth = a.getDimensionPixelSize(R.styleable.CircleProgressView_cpv_stroke_width, 6);
  strokeColor = a.getColor(R.styleable.CircleProgressView_cpv_stroke_color, Color.BLUE);
  showText = a.getBoolean(R.styleable.CircleProgressView_cpv_show_text, true);
  a.recycle(); // 必须调用,释放资源
}

注意:
- 属性 ID 路径为 R.styleable.声明名_属性名
- 每个 getXXX() 方法第二个参数是默认值(当 XML 中未设置时生效)
- a.recycle() 不可省略,避免内存泄漏

5. 小技巧与注意事项

  • 属性名尽量加前缀(如 cpv_),避免和系统属性冲突
  • 同一个 可被多个 复用(例如通用的 textColor
  • 若属性需同时支持 color 和 reference(如背景),可用 format="reference|color"
  • 枚举属性写法示例:

      
      

    读取时用 a.getInt(R.styleable.CircleProgressView_cpv_mode, 0)
  • AS 会自动为 declare-styleable 生成 R.styleable.XXX,无需手动维护

不复杂但容易忽略细节,写好 attrs.xml 是自定义 View 工程化的第一步。