Android自定义View

简述:

    在平时的开发中自定义View是必不可少的,甚至有时候整个复杂的界面全部采用自定义的控件,由此可以看出Android自定义控件的重要程度。先来总结一下自定义View的一般流程:

    ①自定义View的属性
    ②在View的构造方法中获得我们自定义的属性
    ③重写onMesure 
    ④重写onDraw

接下来就以下图的圆环进度条为例分解讲述一下自顶View的流程:

                                                         

自定义View流程:

1、自定义View的属性

      我们先来考虑一下这个View需要什么样的属性,首先需要圆环的半径,其次还需要圆环的宽度、圆环的颜色、进度条的颜色、圆环中间的字体颜色及大小、进度条开始的角度,基本上就这些,如果后来再需要可再添加。我们在values文件夹下创建attrs文件(或者attrs_circleView,只要该文件名以attrs开头就行)。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleView">
        <attr name="radius" format="dimension" />
        <attr name="circleStrokeWidth" format="dimension" />
        <attr name="circleStrokeColor" format="color" />
        <attr name="circleStrokeProgressColor" format="color" />
        <attr name="txtColor" format="color" />
        <attr name="progressStartAngle" format="integer" />
        <attr name="progressEndAngle" format="integer" />
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
</resources>

2、在View的构造方法中获得我们自定义的属性

      获取上述自定义属性的方法:

        //加载自定义属性和属性的默认值
        TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        radius = typeArray.getDimension(R.styleable.CircleView_radius, 100);
        circleStrokeWidth = typeArray.getDimension(R.styleable.CircleView_circleStrokeWidth, 40);
        circleStrokeColor = typeArray.getColor(R.styleable.CircleView_circleStrokeColor, Color.RED);
        circleStrokeProgressColor = typeArray.getColor(R.styleable.CircleView_circleStrokeProgressColor, Color.GREEN);
        txtColor = typeArray.getColor(R.styleable.CircleView_txtColor, Color.RED);
        progressStartAngle = typeArray.getInt(R.styleable.CircleView_progressStartAngle, 90);
        progressEndAngle = typeArray.getInt(R.styleable.CircleView_progressEndAngle, 180);
        textSize = typeArray.getDimension(R.styleable.CircleView_textSize, 30);

        typeArray.recycle();

     所以体现在CircleView类中的代码就是:

public class CircleView extends View {

    private Paint paint;
    private Paint paintProgress;
    private Paint paintTxt;
    private RectF rectF;
    private int circleStrokeColor;
    private int circleStrokeProgressColor;
    private int txtColor;
    private float circleStrokeWidth;
    private float radius;
    private float centerX;
    private float centerY;
    private int progressStartAngle;
    private int progressEndAngle;
    private int currentProgress = 0;
    private int maxProgress = 100;
    private float textSize;
    private int paddingLeft;
    private int paddingTop;
    private int paddingRight;
    private int paddingBottom;

    public CircleView(Context context) {
        this(context, null, -1);
    }

    public CircleView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //加载自定义属性和属性的默认值
        TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        radius = typeArray.getDimension(R.styleable.CircleView_radius, 100);
        circleStrokeWidth = typeArray.getDimension(R.styleable.CircleView_circleStrokeWidth, 40);
        circleStrokeColor = typeArray.getColor(R.styleable.CircleView_circleStrokeColor, Color.RED);
        circleStrokeProgressColor = typeArray.getColor(R.styleable.CircleView_circleStrokeProgressColor, Color.GREEN);
        txtColor = typeArray.getColor(R.styleable.CircleView_txtColor, Color.RED);
        progressStartAngle = typeArray.getInt(R.styleable.CircleView_progressStartAngle, 90);
        progressEndAngle = typeArray.getInt(R.styleable.CircleView_progressEndAngle, 180);
        textSize = typeArray.getDimension(R.styleable.CircleView_textSize, 30);

        typeArray.recycle();

        init();
    }

    那么我们的自定义属性也获取到了,那么接下来就开始画图了,但是在此之前我们还是把需要用到的工具给准备一下吧。我们需要三把画笔,分别用于圆环、进度圆环、圆环中间字符,此外还需要对一些变量进行初始化。

private void init() {
        float halfCircleStrokeWidth = circleStrokeWidth / 2;
        //圆心X、Y轴坐标
        centerX = radius + halfCircleStrokeWidth;
        centerY = radius + halfCircleStrokeWidth;

        //支持padding
        paddingLeft = getPaddingLeft();
        paddingTop = getPaddingTop();
        paddingRight = getPaddingRight();
        paddingBottom = getPaddingBottom();

        //用于画进度条圆弧的矩形
        rectF = new RectF(paddingLeft + halfCircleStrokeWidth, paddingTop + halfCircleStrokeWidth, centerX + paddingLeft + radius, centerY + paddingTop + radius);

        //圆环底层画笔
        paint = new Paint();
        paint.setColor(circleStrokeColor);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(circleStrokeWidth);

        //圆环进度条画笔
        paintProgress = new Paint();
        paintProgress.setColor(circleStrokeProgressColor);
        paintProgress.setAntiAlias(true);
        paintProgress.setStyle(Paint.Style.STROKE);
        paintProgress.setStrokeWidth(circleStrokeWidth);

        //字符串提示的画笔
        paintTxt = new Paint();
        paintTxt.setColor(txtColor);
        paintTxt.setAntiAlias(true);
        paintTxt.setTextAlign(Paint.Align.CENTER);
        paintTxt.setTextSize(textSize);
    }

3、重写onMeasure()方法

    重写之前先了解MeasureSpec的specMode,一共三种类型:
    ①EXACTLY:一般是设置了明确的值或者是MATCH_PARENT
    ②AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT
    ③UNSPECIFIED:表示子布局想要多大就多大,一般情况下这种模式只用在系统中,所以我们不考虑这样情况。

    系统帮我们测量的高度和宽度都是MATCH_PARNET,当我们设置明确的宽度和高度时,系统帮我们测量的结果就是我们设置的结果,当我们设置为WRAP_CONTENT,或者MATCH_PARENT系统帮我们测量的结果就是MATCH_PARENT的长度。所以,当设置了WRAP_CONTENT时,我们需要自己进行测量,即重写onMesure方法”:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //测量并设置CircleView的宽高
        final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        final int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        final int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension((int) (2 * centerX + paddingLeft + paddingRight), (int) (2 * centerY + paddingTop + paddingBottom));
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension((int) (2 * centerX + paddingLeft + paddingRight), heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize, (int) (2 * centerY + paddingTop + paddingBottom));
        }
    }

4、重写onDraw()方法

    在onDraw()方法中一般是执行画图的操作,所以在该方法中我们就做了简单的三件事情:画圆环、画圆弧以及画圆心字符。

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画圆环
        canvas.drawCircle(centerX + paddingLeft, centerY + paddingTop, radius, paint);
        //画圆弧
        progressEndAngle = 360 * currentProgress / maxProgress;
        canvas.drawArc(rectF, progressStartAngle, progressEndAngle, false, paintProgress);
        //画圆心字符
        int percent = (int) (((float) currentProgress / (float) maxProgress) * 100);
        canvas.drawText(percent + "%", centerX + paddingLeft, centerY + paddingTop + textSize / 2, paintTxt);
    }
    OK,到此我们自定义View到此结束,但是如果到此结束的话那我们的圆环进度条怎么更新数据来与用户交互呢,所以我们还需要提供一个与用户交互的方法:用来更新进度。

 /**
     * 方法描述:更新进度
     *
     * @param currentProgress 当前进度值
     */
    public synchronized void updateProgress(int currentProgress) {
        if (currentProgress < 0) {
            throw new IllegalArgumentException("currentProgress must be greater than 0!");
        } else if (currentProgress > maxProgress) {
            this.currentProgress = maxProgress;
        } else {
            this.currentProgress = currentProgress;
            postInvalidate();
        }

    到此我们的核心任务已经结束,当然如果想要这个自定义View支持java代码的创建你也可以像添加更新进度方法updateProgress()一样添加其他方法。


自定义View的使用:

    对于自定义View在XML中的引用需要类名的全路径:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lizhenya.circleview.MainActivity">


    <com.lizhenya.circleview.CircleView
        android:id="@+id/circle_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="40dp"
        app:circleStrokeColor="#00ff00"
        app:circleStrokeProgressColor="#ff0000"
        app:circleStrokeWidth="50dp"
        app:progressStartAngle="270"
        app:radius="100dp"
        app:textSize="30sp"
        app:txtColor="#ff0000" />


</LinearLayout>
    如果在自定义View中引用了自定义属性,需要在该布局文件的最顶层添加:

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

        或者

        ②xmlns:circleview=http://schemas.android.com/apk/res/com.lizhenya.circleview

        注意,“circleview”可以换成其他的任何名字,后面的url地址必须最后一部分必须用上自定义组件的包名。自定义属性了,在属性名前加上“circleview”即可。

    个人喜欢第一种方式,这样不用考虑包名什么的。

源码下载:自定义圆环进度条

对应aar包下载:自定义圆形进度条aar包


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值