应用场景:在自定义View时,除了使用Android系统自带的属性外,还可以通过定义自定义属性并完成引用。
使用步骤:
1、在项目地址:res/value下创建一个attr.xml文件,如下
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyApp"> </span>
<span style="font-size:18px;"><span style="white-space:pre"> </span><attr name="mWidth" format="integer"/>
<attr name="mTextSize" format="dimension"/>
<attr name="mColor" format="color"/>
</declare-styleable>
</resources> </span>
其中,<resource>是根标签,可以在里面定义若干个<declare-styleable>标签
<declare-styleable name="MyApp">中name定义了变量的名称
可以在<declare-styleable>标签内自定义多个属性
如<attr name="mTextSize" format="dimension"/>,其属性的名称为"mTextSize",format指定了该属性类型为dimension,只能表示字体的大小。
其中,format还可以指定其他的类型比如;
reference 表示引用,参考某一资源ID
string 表示字符串
color 表示颜色值
dimension 表示尺寸值
boolean 表示布尔值
integer 表示整型值
float 表示浮点值
fraction 表示百分数
enum 表示枚举值
flag 表示位运算
2、在布局中引用自定义控件时就可以使用自定义的属性了,如
<com.eyu.attrtextdemo.MyApp
android:layout_height="wrap_content"
android:layout_width="wrap_content"
myapp:mTextSize="20sp"
myapp:mColor="#324243"/>
3、在自定义View中引用自定义属性,修改构造函数,
如
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_myColor, 003344);
float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);
paint.setTextSize(textSize);
paint.setColor(textColor);
a.recycle();
其中,在调用结束后,一定要引用recycle()方法,避免对下一次的使用造成影响。