自定义属性
![这里写图片描述](https://img-blog.csdn.net/20170518201102759?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29kZXN1cGVyTWFuMTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="my_name" format="string"/>
<attr name="my_age" format="integer"/>
<attr name="my_bg" format="reference|color"/>
</declare-styleable>
</resources>
<com.example.makura.myapplication.MyView
mydiyattr:my_age="100"
mydiyattr:my_name="zhangsan"
mydiyattr:my_bg="@drawable/testimg"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MyView extends View {
private int myAge;
private String myName;
private Bitmap myBg;
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
/**
* 获取属性的3种方式
* 1.用命名空间去获取
* 2.遍历属性集合
* 3.使用系统工具,获取属性
*/
String name = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_name");
String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_age");
String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_bg");
Log.e("name = ", name);
Log.e("age = ", age);
Log.e("bg = ", bg);
Log.e("分割线1", "-----------------------");
for (int i = 0; i < attrs.getAttributeCount(); i++) {
String attributeName = attrs.getAttributeName(i);
String attributeValue = attrs.getAttributeValue(i);
Log.e(attributeName + " == ", attributeValue);
}
Log.e("分割线2", "-----------------------");
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
for (int i = 0; i < typedArray.getIndexCount(); i++) {
int index = typedArray.getIndex(i);
switch (index) {
case R.styleable.MyView_my_name:
myName = typedArray.getString(index);
break;
case R.styleable.MyView_my_age:
myAge = typedArray.getInt(index,0);
break;
case R.styleable.MyView_my_bg:
Drawable drawable = typedArray.getDrawable(i);
BitmapDrawable bd = (BitmapDrawable) drawable;
myBg = bd.getBitmap();
break;
}
}
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(30);
canvas.drawBitmap(myBg,0,0,paint);
canvas.drawText("myName is"+myName+" myage="+myAge,150,150,paint);
}
}
![这里写图片描述](https://img-blog.csdn.net/20170518201216341?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29kZXN1cGVyTWFuMTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![这里写图片描述](https://img-blog.csdn.net/20170518201224935?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29kZXN1cGVyTWFuMTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)