一、定義與聲明
自定義屬性xml文件.png
在資源文件夾values下新建attr.xml文件
<?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:位或運算
二、具體使用
具體的解析需要自行來做對應的修改:
/**
* 解析自定義屬性
*
* @param context
* @param 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:
//默認設置為16sp,TypeValue也可以把sp轉化為px
mTextSize = attributes.getDimensionPixelSize(attr, (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources()
.getDisplayMetrics()));
break;
}
}
attributes.recycle();
}
上述方法是在自定義View的構造器中調用的:
public CodeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
parseAttr(context, attrs);
}
public CodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
parseAttr(context, attrs);
}