自定义属性之xml文件中自定义的属性

来源:互联网 发布:消息认证算法的简称 编辑:程序博客网 时间:2024/05/16 05:30
在代码中,我们有时会看到代码的布局中或有我们没见过的属性例如
   <com.example.administrator.zdingy.MyAttribute        fanny:my_name="android0220"        fanny:my_age="100"        fanny:my_bg="@drawable/add"        android:layout_width="match_parent"        android:layout_height="match_parent" />

创建attrs.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?><resources>    <!--定义一个名字为MyAttributeView属性集合-->    <declare-styleable name="MyAttribute">        <!--定义一个名字叫my_name并且类型是string的属性-->        <attr name="my_name" format="string"/>        <!--定义一个名字叫my_age并且类型是integer的属性-->        <attr name="my_age" format="integer"/>        <!--定义一个名字叫my_bg并且类型是reference|color的属性-->        <attr name="my_bg" format="reference|color"/>    </declare-styleable></resources>

这是因为使用的自定义属性,下来我们了解一下具体步骤

新建一个自定义类MyAttribute

public class MyAttribute extends View {    private int myAge;    private String myName;    private Bitmap myBg;    public MyAttribute(Context context, AttributeSet attrs) {        super(context, attrs);        //获取属性三种方式        //1.用命名空间取获取//        String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_age");//        String name=attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_name");//        String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_bg");  //参数1.是指在xml文件中写入自定义的语句时,报错时按得Alt+Enter快捷键时生成的语句  //参数2.是在创建attrs.xml文件中,相对应的属性//        Log.e("tag",age+"---"+name+"---"+bg);        //2.遍历属性集合//        for (int i=0;i<attrs.getAttributeCount();i++) {//            System.out.println(attrs.getAttributeName(i)+"=="+attrs.getAttributeValue(i));//        }        //3.使用系统控件        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyAttribute);        for (int i = 0; i < typedArray.getIndexCount(); i++) {            int index = typedArray.getIndex(i);            switch (index) {                case R.styleable.MyAttribute_my_age:                    myAge = typedArray.getInt(index, 0);                    break;                case R.styleable.MyAttribute_my_name:                    myName = typedArray.getString(index);                    break;                case R.styleable.MyAttribute_my_bg:                    Drawable drawable = typedArray.getDrawable(index);                    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;                    myBg = bitmapDrawable.getBitmap();                    break;            }        }        typedArray.recycle();//回收    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        Paint paint = new Paint();        canvas.drawText(myName+"---"+myAge,50,50,paint);        canvas.drawBitmap(myBg,50,50,paint);    }}



0 0
原创粉丝点击