1.自定义一个属性集合attrs.xml
format 常用类型
reference 引用
color 颜色
boolean 布尔值
dimension 尺寸值
float 浮点值
integer 整型值
string 字符串
enum 枚举
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyAttributeView">
<attr name="name" format="string"/>
<attr name="age" format="integer"/>
<attr name="bg" format="reference|color"/>
</declare-styleable>
</resources>
2.引用attrs
xmlns:attrs="http://schemas.android.com/apk/res-auto"
3.使用自定义的属性
<com.example.shuxing.MyAttributeView
android:layout_width="match_parent"
android:layout_height="match_parent"
attrs:name="kkkkkkk"
attrs:age="20"
attrs:bg="@drawable/a"/>
4.获取属性的三种方式
4.1 用命名空间获取
String name= attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","name");
String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","age");
String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","bg");
Log.w("www",name);
Log.w("www",age);
Log.w("www",bg);
02-28 16:07:49.623 3892-3892/? W/www: kkkkkkk
02-28 16:07:49.623 3892-3892/? W/www: 20
02-28 16:07:49.623 3892-3892/? W/www: @2131099649
4.2 遍历属性集合
for(int i=0;i<attrs.getAttributeCount();i++){
Log.w("www",attrs.getAttributeName(i)+attrs.getAttributeValue(i));
}
02-28 16:07:49.624 3892-3892/? W/www: layout_width-1
02-28 16:07:49.624 3892-3892/? W/www: layout_height-1
02-28 16:07:49.624 3892-3892/? W/www: age20
02-28 16:07:49.624 3892-3892/? W/www: bg@2131099649
02-28 16:07:49.624 3892-3892/? W/www: namekkkkkkk
4.3 使用系统工具获取属性
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyAttributeView);
for(int i = 0; i<typedArray.getIndexCount();i++){
int index = typedArray.getIndex(i);
switch (index){
case R.styleable.MyAttributeView_name:
name1 = typedArray.getString(index);
break;
case R.styleable.MyAttributeView_age:
age1 = typedArray.getString(index);
break;
case R.styleable.MyAttributeView_bg:
Drawable drawable = typedArray.getDrawable(index);
BitmapDrawable drawable1 = (BitmapDrawable) drawable;
bg1 = drawable1.getBitmap();
break;
}
}
typedArray.recycle();
显示:
Paint paint = new Paint();
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(name1+age1,10,10,paint);
canvas.drawBitmap(bg1,0,50,paint);
}