理解自定义属性

自定义MyView在布局中引用




  


其中定义的属性在attrs目录下



    
        
        
       
    

MyView的绘制代码

package com.example.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

    private Bitmap mBitmap;
    private int mAnInt;
    private String mString;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //使用系统工具,获取属性
        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_name:
                    mString = typedArray.getString(index);
                    break;
                case R.styleable.MyView_age:
                    mAnInt = typedArray.getInt(index, 0);

                    break;
                case R.styleable.MyView_back:
                    Drawable drawable =  typedArray.getDrawable(index);//把BitmapDrawable实例化所以可以强壮
                    BitmapDrawable bitmapDrawable= (BitmapDrawable) drawable;
                    mBitmap = bitmapDrawable.getBitmap();
                    break;
            }
        }
        typedArray.recycle();
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(50);
        canvas.drawText(mString+mAnInt,80,80,paint);
        canvas.drawBitmap(mBitmap,40,40,paint);
    }
}

理解自定义属性_第1张图片
效果图

你可能感兴趣的:(理解自定义属性)