Android自定义view,圆形的TextView,并通过xml设置属性

Android自定义view设置xml属性

一个圆形的自定义TextView,通过xml来设置背景颜色的属性
在这里插入图片描述

values/attrs

    
        
    

在使用view的xml中

 xmlns:app="http://schemas.android.com/apk/res-auto"
 ...
              

自定义的MyCircleTextView


public class MyCircleTextView extends android.support.v7.widget.AppCompatTextView  {

    private Paint paint;
    float circleRadius = 100;
    float centerX;
    float centerY;
    private String text = "测试";
    int color;
    Rect rect = new Rect();



    public MyCircleTextView(Context context) {
        super(context);
        init();
    }

    public MyCircleTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyCircleTextView);
        String string = typedArray.getString(R.styleable.MyCircleTextView_circleTint);
        color = Color.parseColor(string);
        init();
    }

    public MyCircleTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyCircleTextView);
        String string = typedArray.getString(R.styleable.MyCircleTextView_circleTint);
        color = Color.parseColor(string);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(color);
        paint.setAntiAlias(true);
    }


    @Override
    protected void onDraw(Canvas canvas) {

        centerX = getWidth() / 2;
        centerY = getHeight() / 2;
        circleRadius = centerX;
        //绘制一个圆形
        canvas.drawCircle(centerX, centerY, circleRadius, paint);

        super.onDraw(canvas);


    }
}

你可能感兴趣的:(自定义View)