Andorid 自定义属性介绍

首先要理解什么是属性:水人能控制水流动,火女能控制火燃烧。水的流动,火的燃烧,便是水和火的不同属性。

属性首先要依赖一个载体。水是载体,流动是属性。火是载体,燃烧是属性。

同理,android 自定义属性的载体是View。

TextView 的属性有textSize,CircleView的属性有raidus(半径)。

自定义属性分三步走:

1.在res/values/attrs 文件夹下新建一个名为attrs.xml的文件。

1.Andorid 自定义属性介绍

attrs 文件的内容如下:
    <declare-styleable name="CircleView">
        <attr name="circleColor">color</attr>
        <attr name="radius">float</attr>
    </declare-styleable>
declare-styleable 声明了自定义view的名字,属性名字是radius,属性类型是color和float.属性有很多种,可以百度。

2.自定义一个名字为 CircleView的View

 名字必须命名为CircleView,跟declare-styleable中的名字一致。否则不会显示。

public class CircleView extends View {
    private Paint mCirclePaint;
    private int mCircleColor;
    private float mRadius;
    public CircleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.CircleView);
        if(ta!=null){
            mCircleColor = ta.getColor(R.styleable.CircleView_circleColor, 0);
            mRadius = ta.getFloat(R.styleable.CircleView_radius,0);
            ta.recycle();
        }
        initView();
    }
    private void initView(){
        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(mCircleColor);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int mWidth = 1080;
        int mHeight = 1917;
        canvas.drawCircle(mWidth/2,mHeight/2,mRadius,mCirclePaint);
    }
}
TypedArray简介如下
/**
 * Container for an array of values that were retrieved with
 * {@link Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)}
 * or {@link Resources#obtainAttributes}.  Be
 * sure to call {@link #recycle} when done with them.
 *
 * The indices used to retrieve values from this structure correspond to
 * the positions of the attributes given to obtainStyledAttributes.
 */
TypedArray 可以将attrs中定义的view的属性对应到相应的xml中。注意R.styleable.CircleView的名字必须正确。

3.xml文件中使用

xmlns:app="http://schemas.android.com/apk/res-auto" ,会自动搜索你定义的view属性

Andorid 自定义属性介绍

Andorid 自定义属性介绍