最近有個需求需要實作自定義加載進度條,可以設定加載進度和進度條顔色,于是研究了一下,寫了一個自定義的進度條.
1.自定義進度條代碼如下:

2.完整代碼:
package com.example.tvrecyclerview.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import com.example.tvrecyclerview.R;
/**
* @author: njb
* @date: 2020/11/8 0008 22:55
* @desc:自定義加載進度條
*/
public class CustomProgressBar extends View {
/**
* 進度值最大值
*/
private int mMaxProgress = 100;
/**
* Current progress, can not exceed the max progress.
* 目前進度值,不能超過進度值最大值
*/
private int mCurrentProgress = 0;
/**
* The progress area bar color.
* 目前進度值文本之前的進度條顔色
*/
private int mReachedBarColor;
/**
* The bar unreached area color.
* 目前進度值文本之後的進度條顔色
*/
private int mUnreachedBarColor;
/**
* The progress text color.
* 目前進度值文本的顔色
*/
private int mTextColor;
/**
* The progress text size.
* 目前進度值文本的字型大小
*/
private float mTextSize;
/**
* The height of the reached area.
* 目前進度值文本之前的進度條的高度
*/
private float mReachedBarHeight;
/**
* The height of the unreached area.
* 目前進度值文本之後的進度條的高度
*/
private float mUnreachedBarHeight;
/**
* The suffix of the number.
* 目前進度值的百分比字尾
*/
private String mSuffix = "%";
/**
* The prefix.
* 目前進度值的百分比字首
*/
private String mPrefix = "";
//目前進度值文本的預設顔色
private final int default_text_color = Color.rgb(66, 145, 241);
//目前進度值文本的字型大小
private final float default_text_size;
//目前進度值之前的預設進度條顔色
private final int default_reached_color = Color.rgb(66, 145, 241);
//目前進度值之後的預設進度條顔色
private final int default_unreached_color = Color.rgb(204, 204, 204);
//目前進度值之前文本的預設間距
private final float default_progress_text_offset;
//目前進度值文本之前的進度條的預設高度
private final float default_reached_bar_height;
//目前進度值文本之後的進度條的預設高度
private final float default_unreached_bar_height;
/**
* For save and restore instance of progressbar.
*/
private static final String INSTANCE_STATE = "saved_instance";
private static final String INSTANCE_TEXT_COLOR = "text_color";
private static final String INSTANCE_TEXT_SIZE = "text_size";
private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height";
private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color";
private static final String INSTANCE_UNREACHED_BAR_HEIGHT = "unreached_bar_height";
private static final String INSTANCE_UNREACHED_BAR_COLOR = "unreached_bar_color";
private static final String INSTANCE_MAX = "max";
private static final String INSTANCE_PROGRESS = "progress";
private static final String INSTANCE_SUFFIX = "suffix";
private static final String INSTANCE_PREFIX = "prefix";
private static final String INSTANCE_TEXT_VISIBILITY = "text_visibility";
//預設顯示目前進度值文本 0為顯示,1為不顯示
private static final int PROGRESS_TEXT_VISIBLE = 0;
/**
* The width of the text that to be drawn.
* 要繪制的目前進度值的文本的寬度
*/
private float mDrawTextWidth;
/**
* The drawn text start.
* 要繪制的目前進度值的文本的起始位置
*/
private float mDrawTextStart;
/**
* The drawn text end.
* 要繪制的目前進度值的文本的結束位置
*/
private float mDrawTextEnd;
/**
* The text that to be drawn in onDraw().
* 要繪制的目前進度值的文本
*/
private String mCurrentDrawText;
/**
* The Paint of the reached area.
* 繪制目前進度值文本之前的進度條的畫筆
*/
private Paint mReachedBarPaint;
/**
* The Paint of the unreached area.
* 繪制目前進度值文本之後的進度條的畫筆
*/
private Paint mUnreachedBarPaint;
/**
* The Paint of the progress text.
* 繪制目前進度值文本的的畫筆
*/
private Paint mTextPaint;
/**
* Unreached bar area to draw rect.
* 目前進度值文本之後的進度條(長方形)
*/
private RectF mUnreachedRectF = new RectF(0, 0, 0, 0);
/**
* Reached bar area rect.
* 目前進度值之前文本的進度條(長方形)
*/
private RectF mReachedRectF = new RectF(0, 0, 0, 0);
/**
* The progress text offset.
* 目前進度值之前文本的間距
*/
private float mOffset;
/**
* Determine if need to draw unreached area.
* 是否繪制目前進度值之後的進度條
*/
private boolean mDrawUnreachedBar = true;
/**
* 是否繪制目前進度值之前的進度條
*/
private boolean mDrawReachedBar = true;
/**
* 是否繪制目前進度值文本
*/
private boolean mIfDrawText = true;
/**
* Listener
*/
private OnProgressBarListener mListener;
public enum ProgressTextVisibility {
Visible, Invisible
}
public CustomProgressBar(Context context) {
this(context, null);
}
public CustomProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.CustomProgressBarStyle);
}
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
default_reached_bar_height = dp2px(1.5f);
default_unreached_bar_height = dp2px(1.0f);
default_text_size = sp2px(10);
default_progress_text_offset = dp2px(3.0f);
//擷取自定義屬性
final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomProgressBar,
defStyleAttr, 0);
mReachedBarColor = attributes.getColor(R.styleable.CustomProgressBar_progress_reached_color, default_reached_color);
mUnreachedBarColor = attributes.getColor(R.styleable.CustomProgressBar_progress_unreached_color, default_unreached_color);
mTextColor = attributes.getColor(R.styleable.CustomProgressBar_progress_text_color, default_text_color);
mTextSize = attributes.getDimension(R.styleable.CustomProgressBar_progress_text_size, default_text_size);
mReachedBarHeight = attributes.getDimension(R.styleable.CustomProgressBar_progress_reached_bar_height, default_reached_bar_height);
mUnreachedBarHeight = attributes.getDimension(R.styleable.CustomProgressBar_progress_unreached_bar_height, default_unreached_bar_height);
mOffset = attributes.getDimension(R.styleable.CustomProgressBar_progress_text_offset, default_progress_text_offset);
int textVisible = attributes.getInt(R.styleable.CustomProgressBar_progress_text_visibility, PROGRESS_TEXT_VISIBLE);
if (textVisible != PROGRESS_TEXT_VISIBLE) {
mIfDrawText = false;
}
setProgress(attributes.getInt(R.styleable.CustomProgressBar_progress_current, 0));
setMax(attributes.getInt(R.styleable.CustomProgressBar_progress_max, 100));
//回收 TypedArray,用于後續調用時可複用之。回收到TypedArrayPool池中,以備後用
attributes.recycle();
initializePainters();
}
@Override
protected int getSuggestedMinimumWidth() {
return (int) mTextSize;
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max((int) mTextSize, Math.max((int) mReachedBarHeight, (int) mUnreachedBarHeight));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/**
* MeasureSpec參數的值為int型,分為高32位和低16為,
* 高32位儲存的是specMode,低16位表示specSize,
*
* specMode分三種:
1、MeasureSpec.UNSPECIFIED,父視圖不對子視圖施加任何限制,子視圖可以得到任意想要的大小;
2、MeasureSpec.EXACTLY,父視圖希望子視圖的大小是specSize中指定的大小;
3、MeasureSpec.AT_MOST,子視圖的大小最多是specSize中的大小。
*/
setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false));
}
private int measure(int measureSpec, boolean isWidth) {
int result;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom();
/**
父決定子的确切大小,子被限定在給定的邊界裡,忽略本身想要的大小。
(當設定width或height為match_parent時,模式為EXACTLY,因為子view會占據剩餘容器的空間,是以它大小是确定的)
*/
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else {
result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();
result += padding;
/**
*子最大可以達到的指定大小
* (當設定為wrap_content時,模式為AT_MOST, 表示子view的大小最多是多少,這樣子view會根據這個上限來設定自己的尺寸)
*/
if (mode == MeasureSpec.AT_MOST) {
if (isWidth) {
result = Math.max(result, size);
} else {
result = Math.min(result, size);
}
}
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
//如果要繪制目前進度值文本
if (mIfDrawText) {
calculateDrawRectF();
} else {
calculateDrawRectFWithoutProgressText();
}
//如果要繪制目前進度值之前的進度條
if (mDrawReachedBar) {
canvas.drawRect(mReachedRectF, mReachedBarPaint);
}
//如果要繪制目前進度值之後的進度條
if (mDrawUnreachedBar) {
canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint);
}
//繪制目前進度值文本
if (mIfDrawText)
canvas.drawText(mCurrentDrawText, mDrawTextStart, mDrawTextEnd, mTextPaint);
}
/**
* 初始化畫筆
*/
private void initializePainters() {
mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mReachedBarPaint.setColor(mReachedBarColor);
mUnreachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mUnreachedBarPaint.setColor(mUnreachedBarColor);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setColor(mTextColor);
mTextPaint.setTextSize(mTextSize);
}
/**
* 計算不要繪制目前進度值文本時 圖形的各個屬性
*/
private void calculateDrawRectFWithoutProgressText() {
//目前進度值不畫
//目前進度值之前的進度條(長方形)的屬性
mReachedRectF.left = getPaddingLeft();
mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;
mReachedRectF.right =
(getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress()
+ getPaddingLeft();
mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;
//目前進度值之後的進度條(長方形)的屬性
mUnreachedRectF.left = mReachedRectF.right;
mUnreachedRectF.right = getWidth() - getPaddingRight();
mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f;
mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f;
}
/**
* 計算要繪制目前進度值文本時 圖形的各個屬性
*/
@SuppressLint("DefaultLocale")
private void calculateDrawRectF() {
//要繪制的目前進度值的文本
mCurrentDrawText = String.format("%d", getProgress() * 100 / getMax());
mCurrentDrawText = mPrefix + mCurrentDrawText + mSuffix;
//要繪制的目前進度值的文本的寬度
mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText);
//如果目前進度值為0,則不繪制目前進度值之前的進度條
if (getProgress() == 0) {
mDrawReachedBar = false;
mDrawTextStart = getPaddingLeft();
}
//否則繪制目前進度值文本之前的進度條
else {
mDrawReachedBar = true;
//目前進度值文本之前的進度條(長方形)的屬性
mReachedRectF.left = getPaddingLeft();
mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;
mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress()
- mOffset + getPaddingLeft();
mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;
//目前進度值的文本的起始位置
mDrawTextStart = (mReachedRectF.right + mOffset);
}
//目前進度值的文本的結束位置
mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f));
//如果畫不下目前進度值的文本了,就重新計算下目前進度值的文本的起始位置和目前進度值之前的進度條(長方形)的右邊
if ((mDrawTextStart + mDrawTextWidth) >= getWidth() - getPaddingRight()) {
mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth;
mReachedRectF.right = mDrawTextStart - mOffset;
}
//目前進度值文本之後的進度條的起始位置
float unreachedBarStart = mDrawTextStart + mDrawTextWidth + mOffset;
//如果畫不下進度值文本之後的進度條了,就不畫進度值之後的進度條
if (unreachedBarStart >= getWidth() - getPaddingRight()) {
mDrawUnreachedBar = false;
} else {
mDrawUnreachedBar = true;
//目前進度值文本之後的進度條(長方形)的屬性
mUnreachedRectF.left = unreachedBarStart;
mUnreachedRectF.right = getWidth() - getPaddingRight();
mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f;
mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f;
}
}
/**
* Get progress text color.
* 擷取目前進度值文本的顔色
*
* @return progress text color.
*/
public int getTextColor() {
return mTextColor;
}
/**
* Get progress text size.
* 擷取目前進度值文本的字型大小
*
* @return progress text size.
*/
public float getProgressTextSize() {
return mTextSize;
}
/**
* 擷取目前進度值文本之後的進度條顔色
*/
public int getUnreachedBarColor() {
return mUnreachedBarColor;
}
/**
* 擷取目前進度值文本之前的進度條顔色
*/
public int getReachedBarColor() {
return mReachedBarColor;
}
/**
* 擷取進度條的目前進度值
*/
public int getProgress() {
return mCurrentProgress;
}
/**
* 擷取進度條的最大值
*/
public int getMax() {
return mMaxProgress;
}
/**
* 擷取目前進度值文本之前的進度條的高度
*/
public float getReachedBarHeight() {
return mReachedBarHeight;
}
/**
* 擷取目前進度值文本之後的進度條的高度
*/
public float getUnreachedBarHeight() {
return mUnreachedBarHeight;
}
/**
* 設定目前進度值文本的字型大小
*
* @param textSize 目前進度值文本的字型大小
*/
public void setProgressTextSize(float textSize) {
this.mTextSize = textSize;
mTextPaint.setTextSize(mTextSize);
invalidate();
}
/**
* 設定目前進度值文本的顔色
*
* @param textColor 目前進度值文本的顔色
*/
public void setProgressTextColor(int textColor) {
this.mTextColor = textColor;
mTextPaint.setColor(mTextColor);
invalidate();
}
/**
* 設定目前進度值文本之後的進度條顔色
*
* @param barColor 目前進度值文本之後的進度條顔色
*/
public void setUnreachedBarColor(int barColor) {
this.mUnreachedBarColor = barColor;
mUnreachedBarPaint.setColor(mUnreachedBarColor);
invalidate();
}
/**
* 設定目前進度值文本之前的進度條顔色
*
* @param progressColor 目前進度值文本之前的進度條顔色
*/
public void setReachedBarColor(int progressColor) {
this.mReachedBarColor = progressColor;
mReachedBarPaint.setColor(mReachedBarColor);
invalidate();
}
/**
* 設定目前進度值文本之前的進度條的高度
*
* @param height 目前進度值文本之前的進度條的高度
*/
public void setReachedBarHeight(float height) {
mReachedBarHeight = height;
}
/**
* 設定目前進度值文本之後的進度條的高度
*
* @param height 目前進度值文本之後的進度條的高度
*/
public void setUnreachedBarHeight(float height) {
mUnreachedBarHeight = height;
}
/**
* 設定進度值的最大值
*
* @param maxProgress 進度值的最大值
*/
public void setMax(int maxProgress) {
if (maxProgress > 0) {
this.mMaxProgress = maxProgress;
invalidate();
}
}
/**
* 設定目前進度值文本的字尾
*
* @param suffix 目前進度值文本的字尾
*/
public void setSuffix(String suffix) {
if (suffix == null) {
mSuffix = "";
} else {
mSuffix = suffix;
}
}
/**
* 擷取目前進度值文本的字尾
*/
public String getSuffix() {
return mSuffix;
}
/**
* 設定目前進度值文本的字首
*
* @param prefix 目前進度值文本的字首
*/
public void setPrefix(String prefix) {
if (prefix == null)
mPrefix = "";
else {
mPrefix = prefix;
}
}
/**
* 擷取目前進度值文本的字首
*/
public String getPrefix() {
return mPrefix;
}
/**
* 設定進度條的目前進度值增加
*
* @param by 增加多少
*/
public void incrementProgressBy(int by) {
if (by > 0) {
setProgress(getProgress() + by);
}
if (mListener != null) {
//回調onProgressChange()方法來處理進度值變化後的事件
mListener.onProgressChange(getProgress(), getMax());
}
}
/**
* 設定目前進度值
*
* @param progress 目前進度值
*/
public void setProgress(int progress) {
if (progress <= getMax() && progress >= 0) {
this.mCurrentProgress = progress;
invalidate();
}
}
@Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
bundle.putInt(INSTANCE_TEXT_COLOR, getTextColor());
bundle.putFloat(INSTANCE_TEXT_SIZE, getProgressTextSize());
bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT, getReachedBarHeight());
bundle.putFloat(INSTANCE_UNREACHED_BAR_HEIGHT, getUnreachedBarHeight());
bundle.putInt(INSTANCE_REACHED_BAR_COLOR, getReachedBarColor());
bundle.putInt(INSTANCE_UNREACHED_BAR_COLOR, getUnreachedBarColor());
bundle.putInt(INSTANCE_MAX, getMax());
bundle.putInt(INSTANCE_PROGRESS, getProgress());
bundle.putString(INSTANCE_SUFFIX, getSuffix());
bundle.putString(INSTANCE_PREFIX, getPrefix());
bundle.putBoolean(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility());
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
mTextColor = bundle.getInt(INSTANCE_TEXT_COLOR);
mTextSize = bundle.getFloat(INSTANCE_TEXT_SIZE);
mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT);
mUnreachedBarHeight = bundle.getFloat(INSTANCE_UNREACHED_BAR_HEIGHT);
mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR);
mUnreachedBarColor = bundle.getInt(INSTANCE_UNREACHED_BAR_COLOR);
initializePainters();
setMax(bundle.getInt(INSTANCE_MAX));
setProgress(bundle.getInt(INSTANCE_PROGRESS));
setPrefix(bundle.getString(INSTANCE_PREFIX));
setSuffix(bundle.getString(INSTANCE_SUFFIX));
setProgressTextVisibility(bundle.getBoolean(INSTANCE_TEXT_VISIBILITY) ? ProgressTextVisibility.Visible : ProgressTextVisibility.Invisible);
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
return;
}
super.onRestoreInstanceState(state);
}
/**
* dp轉px
*/
public float dp2px(float dp) {
final float scale = getResources().getDisplayMetrics().density;
return dp * scale + 0.5f;
}
/**
* sp轉px
*/
public float sp2px(float sp) {
final float scale = getResources().getDisplayMetrics().scaledDensity;
return sp * scale;
}
/**
* 設定是否繪制目前進度值文本
*/
public void setProgressTextVisibility(ProgressTextVisibility visibility) {
mIfDrawText = visibility == ProgressTextVisibility.Visible;
invalidate();
}
/**
* 擷取是否繪制目前進度值文本
*/
public boolean getProgressTextVisibility() {
return mIfDrawText;
}
/**
* 設定進度值變化時的監聽器
*/
public void setOnProgressBarListener(OnProgressBarListener listener) {
mListener = listener;
}
}
3.進度回調監聽代碼:
/**
* @author: njb
* @Date: 2020/9/29 17:26
* @desc:進度調皮回調
*/
public interface OnProgressBarListener {
void onProgressChange(int progress, int max);
}
4.在布局中的使用:
<com.example.tvrecyclerview.view.CustomProgressBar
android:id="@+id/numberbar"
style="@style/customProgressBar_Default"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="52dp"
android:layout_marginEnd="52dp"
android:layout_marginBottom="52dp"
android:padding="20dp"
android:visibility="visible"
custom:progress_current="0"
custom:progress_max="100"
custom:ignore="MissingConstraints" />
5.attrs.xml檔案代碼如下:
<declare-styleable name="CustomProgressBar">
<attr name="progress_current" format="integer"/>
<attr name="progress_max" format="integer"/>
<attr name="progress_unreached_color" format="color"/>
<attr name="progress_reached_color" format="color"/>
<attr name="progress_reached_bar_height" format="dimension"/>
<attr name="progress_unreached_bar_height" format="dimension"/>
<attr name="progress_text_size" format="dimension"/>
<attr name="progress_text_color" format="color"/>
<attr name="progress_text_offset" format="dimension"/>
<attr name="progress_text_visibility" format="enum">
<enum name="visible" value="0"/>
<enum name="invisible" value="1"/>
</attr>
</declare-styleable>
<declare-styleable name="Themes">
<attr name="CustomProgressBarStyle" format="reference"/>
</declare-styleable>
6.style.xml檔案代碼如下:
<style name="customProgressBar_Default">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">match_parent</item>
<item name="progress_max">100</item>
<item name="progress_current">0</item>
<item name="progress_unreached_color">#0FFFFF</item>
<item name="progress_reached_color">#2151FF</item>
<item name="progress_text_size">10sp</item>
<item name="progress_text_color">#FBFCFE</item>
<item name="progress_reached_bar_height">1.5dp</item>
<item name="progress_unreached_bar_height">0.75dp</item>
</style>
7.運作的效果如下: