一、定义与声明
在资源文件夹 values 下新建 attr.xml 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | <?xml version="1.0" encoding="utf-8"?> <resources>
      <attr name="text" format="string"/>     <attr name="textColor" format="color"/>     <attr name="textSize" format="dimension"/>
      <declare-styleable name="CodeView">         <attr name="text"></attr>         <attr name="textColor"></attr>         <attr name="textSize"></attr>     </declare-styleable>
  </resources>
 
  | 
 
其中 CodeView 是自定义 styleable 名,可以随意取
format 有以下几种:
- reference:参考某一资源 ID
 
- color:颜色值
 
- boolean:布尔值
 
- dimension:尺寸值
 
- float:浮点值
 
- integer:整型值
 
- string:字符串
 
- fraction:百分数
 
- enum:枚举值
 
- flag:位或运算
 
二、具体使用
具体的解析需要自行来做对应的修改(以我自己写的 parseAttr 方法为例子):
自定义 View 的构造器中调用 parseAttr()自定义解析并处理。
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
   | class CustomView extends View {
      public CodeView(Context context) {         this(context, null);     }
      public CodeView(Context context, @Nullable AttributeSet attrs) {         this(context, attrs, 0);     }
      public CodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {         super(context, attrs, defStyleAttr);         parseAttr(context, attrs);     }
      
 
 
 
 
      private void parseAttr(Context context, @Nullable AttributeSet attrs) {         TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CodeView);         int num = attributes.getIndexCount();         for (int i = 0; i < num; i++) {             int attr = attributes.getIndex(i);             switch (attr) {                 case R.styleable.CodeView_text:                     mText = attributes.getString(attr);                     break;                 case R.styleable.CodeView_textColor:                                          mTextColor = attributes.getColor(attr, Color.BLACK);                     break;                 case R.styleable.CodeView_textSize:                                          mTextSize = attributes.getDimensionPixelSize(attr, (int) TypedValue                             .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources()                             .getDisplayMetrics()));                     break;             }         }         attributes.recycle();     } }
 
  |