Android自定义View圆形百分比控件(一)

所属分类: 软件编程 / Android 阅读数: 42
收藏 0 赞 0 分享

做一个自定义View的小练习,效果如下

这里写图片描述

只需要画一个圆、一个圆弧、一个百分比文本,添加一个点击事件,传入百分比重绘

1、在res/values文件夹下新建attrs.xml文件,编写自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="CirclePercentView" >
    <attr name="circleBg" format="color"/>
    <attr name="arcColor" format="color"/>
    <attr name="arcWidth" format="dimension"/>
    <attr name="percentTextColor" format="color"/>
    <attr name="percentTextSize" format="dimension"/>
    <attr name="radius" format="dimension"/>
  </declare-styleable>
</resources>

2、新建CirclePercentView继承View,重写构造方法:

public CirclePercentView(Context context) {
    this(context, null);
  }

  public CirclePercentView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public CirclePercentView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

3、在第三个构造方法中获取自定义属性的值:

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CirclePercentView, defStyleAttr, 0);
    mCircleColor = ta.getColor(R.styleable.CirclePercentView_circleBg, 0xff8e29fa);
    mArcColor = ta.getColor(R.styleable.CirclePercentView_arcColor, 0xffffee00);
    mArcWidth = ta.getDimensionPixelSize(R.styleable.CirclePercentView_arcWidth, DensityUtils.dp2px(context, 16));
    mPercentTextColor = ta.getColor(R.styleable.CirclePercentView_arcColor, 0xffffee00);
    mPercentTextSize = ta.getDimensionPixelSize(R.styleable.CirclePercentView_percentTextSize, DensityUtils.sp2px(context, 16));
    mRadius = ta.getDimensionPixelSize(R.styleable.CirclePercentView_radius, DensityUtils.dp2px(context, 100));
    ta.recycle();

4、创建画图所使用的对象,如Paint、Rect、RectF:

    mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCirclePaint.setStyle(Paint.Style.FILL);
    mCirclePaint.setColor(mCircleColor);

    mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mArcPaint.setStyle(Paint.Style.STROKE);
    mArcPaint.setStrokeWidth(mArcWidth);
    mArcPaint.setColor(mArcColor);
    mArcPaint.setStrokeCap(Paint.Cap.ROUND);//使圆弧两头圆滑

    mPercentTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPercentTextPaint.setStyle(Paint.Style.STROKE);
    mPercentTextPaint.setColor(mPercentTextColor);
    mPercentTextPaint.setTextSize(mPercentTextSize);

    mArcRectF = new RectF();//圆弧的外接矩形

    mTextBound = new Rect();//文本的范围矩形

5、重写onMeasure()方法,计算自定义View的宽高:

 @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(measureDimension(widthMeasureSpec), measureDimension(heightMeasureSpec));
  }

  private int measureDimension(int measureSpec) {
    int result;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    if (specMode == MeasureSpec.EXACTLY) {//精确地,代表宽高为定值或者match_parent时
      result = specSize;
    } else {
      result = 2 * mRadius;
      if (specMode == MeasureSpec.AT_MOST) {//最大地,代表宽高为wrap_content时
        result = Math.min(result, specSize);
      }
    }
    return result;
  }

6、重写onDraw()方法,绘制圆、圆弧和百分比文本,注意坐标的计算:

这里写图片描述

  @Override
  protected void onDraw(Canvas canvas) {
    //画圆
    canvas.drawCircle(getWidth() / 2, getHeight() / 2, mRadius, mCirclePaint);

    //画圆弧
    mArcRectF.set(getWidth() / 2 - mRadius + mArcWidth / 2, getHeight() / 2 - mRadius + mArcWidth / 2
        , getWidth() / 2 + mRadius - mArcWidth / 2, getHeight() / 2 + mRadius - mArcWidth / 2);
    canvas.drawArc(mArcRectF, 270, 360 * mCurPercent / 100, false, mArcPaint);

    String text = mCurPercent + "%";
    //计算文本宽高
    mPercentTextPaint.getTextBounds(text, 0, String.valueOf(text).length(), mTextBound);
    //画百分比文本
    canvas.drawText(text, getWidth() / 2 - mTextBound.width() / 2
        , getHeight() / 2 + mTextBound.height() / 2, mPercentTextPaint);
  }

7、给这个view设置点击事件,暴露一个动态设置百分比的方法:

  public void setCurPercent(float curPercent) {
    ValueAnimator anim = ValueAnimator.ofFloat(mCurPercent, curPercent);
    //动画时长由百分比大小决定
    anim.setDuration((long) (Math.abs(mCurPercent - curPercent) * 20));
    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        float value = (float) animation.getAnimatedValue();
        mCurPercent = (float) (Math.round(value * 10)) / 10;//四舍五入保留到小数点后两位
        invalidate();//重绘,重走onDraw()方法,这也是不能再onDraw()中创建对象的原因
      }
    });
    anim.start();
  }

  public void setOnCircleClickListener(OnClickListener onClickListener) {
    this.mOnClickListener = onClickListener;
  }

    //在构造方法中
    setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (mOnClickListener != null) {
          mOnClickListener.onClick(CirclePercentView.this);
        }
      }
    });

8、在activity_main.xml布局文件中使用该View:

<!-- 使用自定义命名空间namespace,cpv是该控件名的首字母缩写,可以随意取 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:cpv="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <!-- cpv后面的属性名对应attrs.xml文件中的自定义属性名 -->
  <com.monkey.customviewdemo.view.CirclePercentView
    android:id="@+id/circlePercentView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    cpv:arcColor="#ffee00"
    cpv:arcWidth="@dimen/activity_horizontal_margin"
    cpv:circleBg="#8e29fa"
    cpv:percentTextColor="#ffee00"
    cpv:percentTextSize="16sp"
    cpv:radius="100dp" />
</RelativeLayout>

9、在MainActivity.java中设置监听,传入百分比:

  mCirclePercentView = (CirclePercentView) findViewById(R.id.circlePercentView);
  mCirclePercentView.setOnCircleClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      float percent = (float) (Math.random() * 99 + 1);
      mCirclePercentView.setCurPercent(percent);
    }
  });


代码下载地址:
https://github.com/MonkeyMushroom/CirclePercentView/tree/master

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Android网络编程之获取网络上的Json数据实例

这篇文章主要介绍了Android网络编程之获取网络上的Json数据实例,本文用完整的代码实例讲解了在Android中读取网络中Json数据的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中的windowSoftInputMode属性详解

这篇文章主要介绍了Android中的windowSoftInputMode属性详解,本文对windowSoftInputMode的9个属性做了详细总结,需要的朋友可以参考下
收藏 0 赞 0 分享

Android网络编程之UDP通信模型实例

这篇文章主要介绍了Android网络编程之UDP通信模型实例,本文给出了服务端代码和客户端代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中使用ListView实现漂亮的表格效果

这篇文章主要介绍了Android中使用ListView实现漂亮的表格效果,本文用详细的代码实例创建了一个股票行情表格,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中刷新界面的二种方法

这篇文章主要介绍了Android中刷新界面的二种方法,本文使用Handler、postInvalidate两种方法实现界面刷新,需要的朋友可以参考下
收藏 0 赞 0 分享

Android SDK三种更新失败及其解决方法

这篇文章主要介绍了Android SDK三种更新失败及其解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(一)

Android3.0(API level 11)开始,Android设备不再需要专门的菜单键。随着这种变化,Android app应该取消对传统6项菜单的依赖。取而代之的是提供anction bar来提供基本的用户功能
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(二)

这次将继续上一篇文章没有讲完的Menu的学习,上下文菜单(Context menu)和弹出菜单(Popup menu)
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(三)

今天继续昨天没有讲完的Menu的学习,主要是Popup Menu的学习,需要的朋友可以参考下
收藏 0 赞 0 分享

Android显示网络图片实例

这篇文章主要介绍了Android显示网络图片的方法,以实例形式展示了Android程序显示网络图片的方法,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多