本篇博文是按照http://www.imooc.com/learn/657教程中的学习过程,代码是按照视频中原作者的思路来敲的,虽然只是模仿,但我觉得这是学习自定义view的必经之路,所以还是把我所学到的东西拿出来与大家一起分享。
先贴出一张progressBar的gif图,其中有水平的进度条,和圆形的进度条:
这里我们的实现的思路是继承的progressBar,然后重新去测量和绘制相关代码,我们直接贴出源码:
attrs相关属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="progress_unreach_color" format="color" />
<attr name="progress_unreach_height" format="dimension" />
<attr name="progress_reach_color" format="color" />
<attr name="progress_reach_height" format="dimension" />
<attr name="progress_text_color" format="color" />
<attr name="progress_text_size" format="dimension" />
<attr name="progress_text_offset" format="dimension" />
<declare-styleable name="HorizontalProgressbarWithProgress">
<attr name="progress_unreach_color" />
<attr name="progress_unreach_height" />
<attr name="progress_reach_color" />
<attr name="progress_reach_height" />
<attr name="progress_text_color" />
<attr name="progress_text_size" />
<attr name="progress_text_offset" />
</declare-styleable>
<declare-styleable name="RoundProgressbarWithProgress">
<attr name="radius" format="dimension" />
</declare-styleable>
</resources>
水平进度条源码:
package com.example.asiatravel.learnprogressbar.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;
import com.example.asiatravel.learnprogressbar.R;
/**
* Created by kuangxiaoguo on 16/9/8.
*
* 水平进度条
*/
public class HorizontalProgressbarWithProgress extends ProgressBar {
private static final int DEFAULT_TEXT_SIZE = 10;
private static final int DEFAULT_TEXT_COLOR = 0xFFFC00D1;
private static final int DEFAULT_COLOR_UNREACH = 0XFFD3D6DA;
private static final int DEFAULT_HEIGHT_UNREACH = 2;
private static final int DEFAULT_COLOR_REACH = DEFAULT_TEXT_COLOR;
private static final int DEFAULT_HEIGHT_REACH = 2;
private static final int DEFAULT_TEXT_OFFSET = 10;
protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
protected int mTextColor = DEFAULT_TEXT_COLOR;
protected int mUnReachColor = DEFAULT_COLOR_UNREACH;
protected int mUNReachHeight = dp2px(DEFAULT_HEIGHT_UNREACH);
protected int mReachColor = DEFAULT_COLOR_REACH;
protected int mReachHeight = dp2px(DEFAULT_HEIGHT_REACH);
protected int mTextOffSet = dp2px(DEFAULT_TEXT_OFFSET);
protected Paint mPaint = new Paint();