Android自定义控件(1)——Quick Start

一、目标

绘制图形,通过设置属性改变颜色

二、效果

三、步骤

1. 在values下新建attrs.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="linecolor" format="color"/>
    </declare-styleable>
</resources>

attr项为属性名称和格式

2. 新建继承自View的类CustomView.java

在构造方法获取属性

public CustomView(Context context, AttributeSet attrs){
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);

        try{
            lineColor = a.getColor(R.styleable.CustomView_linecolor, Color.parseColor("#000000"));
        }
        finally {
            init();
            a.recycle();
        }
    }

重写onDraw()

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float centerX = getWidth()/2;
        float centerY = getHeight()/2;

        myPaint.setStyle(Paint.Style.STROKE);
        myPaint.setStrokeWidth(5);

        canvas.drawCircle(centerX, centerY, 200, myPaint);
        canvas.drawCircle(centerX-70, centerY-50, 40, myPaint);
        canvas.drawCircle(centerX+70, centerY-50, 40, myPaint);

        myPaint.setStyle(Paint.Style.FILL);

        canvas.drawCircle(centerX-70, centerY-40, 25, myPaint);
        canvas.drawCircle(centerX+70, centerY-40, 25, myPaint);

        //drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)
        RectF rectF = new RectF(centerX-80, centerY+20, centerX+80, centerY+100);
        myPaint.setStyle(Paint.Style.STROKE);
        canvas.drawArc(rectF, 0, 180, false, myPaint);

    }
3. 引用控件

添加xmlns:custom="http://schemas.android.com/apk/res-auto"

<com.study.app.customview.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:linecolor="#DB6958"/>

参考: https://developer.android.com/training/custom-views/create-view.html
源代码 下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值