Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 Android 圓形進度條:屬性、onDraw 與 thread-safe 更新

編輯:關於 Android 程式設計

我們再用一個小實例,把「自定義 View + 自定義屬性」這套組合完整走一遍——這次要畫一個帶進度的圓形進度條。

先來看成果:

從上圖可以看到,我們可以自訂:圓環顏色、進度弧顏色、是否顯示百分比、百分比文字顏色與大小、圓環粗細,以及進度是空心(STROKE)還是實心(FILL)。變化相當多,接下來就一步步拆解。

步驟一:在 values 下新增 attrs.xml

定義各項屬性,不同屬性對應不同的 format:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="RoundProgressBar">
        <attr name="roundColor" format="color"/>
        <attr name="roundProgressColor" format="color"/>
        <attr name="roundWidth" format="dimension"></attr>
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
        <attr name="max" format="integer"></attr>
        <attr name="textIsDisplayable" format="boolean"></attr>
        <attr name="style">
            <enum name="STROKE" value="0"></enum>
            <enum name="FILL" value="1"></enum>
        </attr>
    </declare-styleable>
</resources>

步驟二:在建構子中取值

呼叫 context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar) 取得 TypedArray,再逐一取出屬性:

roundColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundColor, Color.RED);
roundProgressColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundProgressColor, Color.GREEN);
textColor = mTypedArray.getColor(R.styleable.RoundProgressBar_textColor, Color.GREEN);
textSize = mTypedArray.getDimension(R.styleable.RoundProgressBar_textSize, 15);
roundWidth = mTypedArray.getDimension(R.styleable.RoundProgressBar_roundWidth, 5);
max = mTypedArray.getInteger(R.styleable.RoundProgressBar_max, 100);
textIsDisplayable = mTypedArray.getBoolean(R.styleable.RoundProgressBar_textIsDisplayable, true);
style = mTypedArray.getInt(R.styleable.RoundProgressBar_style, 0);

以 getColor() 為例:第一個參數是 XML 中宣告的屬性資源 ID,第二個參數是預設值。若使用者沒在 XML 中指定 roundColor,就會採用 Color.RED。這個「一定要有預設值」的習慣能避免大量空值問題。

步驟三:完整 View 程式碼

package com.example.roundprogressbar;

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.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.example.circlepregress.R;

/**
 * 仿 iPhone 風格的圓形進度條,thread-safe,可直接在子執行緒更新進度
 */
public class RoundProgressBar extends View {

    /** 畫筆物件 */
    private Paint paint;

    /** 圓環顏色 */
    private int roundColor;
    /** 進度弧顏色 */
    private int roundProgressColor;
    /** 中央百分比文字顏色 */
    private int textColor;
    /** 中央百分比文字大小 */
    private float textSize;
    /** 圓環粗細 */
    private float roundWidth;
    /** 最大進度 */
    private int max;
    /** 目前進度 */
    private int progress;
    /** 是否顯示中央進度文字 */
    private boolean textIsDisplayable;
    /** 進度風格:實心或空心 */
    private int style;

    public static final int STROKE = 0;
    public static final int FILL = 1;

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

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

    public RoundProgressBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        paint = new Paint();
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar);

        // 取得自定義屬性與預設值
        roundColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundColor, Color.RED);
        roundProgressColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundProgressColor, Color.GREEN);
        textColor = mTypedArray.getColor(R.styleable.RoundProgressBar_textColor, Color.GREEN);
        textSize = mTypedArray.getDimension(R.styleable.RoundProgressBar_textSize, 15);
        roundWidth = mTypedArray.getDimension(R.styleable.RoundProgressBar_roundWidth, 5);
        max = mTypedArray.getInteger(R.styleable.RoundProgressBar_max, 100);
        textIsDisplayable = mTypedArray.getBoolean(R.styleable.RoundProgressBar_textIsDisplayable, true);
        style = mTypedArray.getInt(R.styleable.RoundProgressBar_style, 0);

        mTypedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        /** 畫最外層的大圓環 */
        int centre = getWidth() / 2;                     // 圓心座標
        int radius = (int) (centre - roundWidth / 2);    // 圓環半徑

        paint.setColor(roundColor);
        paint.setStyle(Paint.Style.STROKE);   // 空心
        paint.setStrokeWidth(roundWidth);
        paint.setAntiAlias(true);             // 消除鋸齒
        canvas.drawCircle(centre, centre, radius, paint);
        Log.e("log", centre + "");

        /** 畫進度百分比 */
        paint.setStrokeWidth(0);
        paint.setColor(textColor);
        paint.setTextSize(textSize);
        paint.setTypeface(Typeface.DEFAULT_BOLD);

        // 先轉 float 再除法,否則整數除法會得到 0
        int percent = (int) (((float) progress / (float) max) * 100);
        float textWidth = paint.measureText(percent + "%");   // 量文字寬度以便置中

        if (textIsDisplayable && percent != 0 && style == STROKE) {
            canvas.drawText(percent + "%", centre - textWidth / 2, centre + textSize / 2, paint);
        }

        /** 畫進度弧 */
        paint.setStrokeWidth(roundWidth);
        paint.setColor(roundProgressColor);

        // 定義圓弧的大小與形狀範圍
        RectF oval = new RectF(centre - radius, centre - radius,
                centre + radius, centre + radius);

        switch (style) {
            case STROKE: {
                paint.setStyle(Paint.Style.STROKE);
                canvas.drawArc(oval, 0, 360 * progress / max, false, paint);
                break;
            }
            case FILL: {
                paint.setStyle(Paint.Style.FILL_AND_STROKE);
                if (progress != 0) {
                    canvas.drawArc(oval, 0, 360 * progress / max, true, paint);
                }
                break;
            }
        }
    }

    public synchronized int getMax() {
        return max;
    }

    /** 設定進度上限 */
    public synchronized void setMax(int max) {
        if (max < 0) {
            throw new IllegalArgumentException("max not less than 0");
        }
        this.max = max;
    }

    public synchronized int getProgress() {
        return progress;
    }

    /**
     * 設定進度。此為 thread-safe 控制項,考慮多執行緒問題需同步;
     * 使用 postInvalidate() 可在非 UI 執行緒刷新畫面
     */
    public synchronized void setProgress(int progress) {
        if (progress < 0) {
            throw new IllegalArgumentException("progress not less than 0");
        }
        if (progress > max) {
            progress = max;
        }
        this.progress = progress;
        postInvalidate();
    }

    public int getCricleColor() { return roundColor; }
    public void setCricleColor(int cricleColor) { this.roundColor = cricleColor; }

    public int getCricleProgressColor() { return roundProgressColor; }
    public void setCricleProgressColor(int cricleProgressColor) {
        this.roundProgressColor = cricleProgressColor;
    }

    public int getTextColor() { return textColor; }
    public void setTextColor(int textColor) { this.textColor = textColor; }

    public float getTextSize() { return textSize; }
    public void setTextSize(float textSize) { this.textSize = textSize; }

    public float getRoundWidth() { return roundWidth; }
    public void setRoundWidth(float roundWidth) { this.roundWidth = roundWidth; }
}

步驟四:在 XML 中使用

使用前,必須在佈局最上層宣告自定義屬性的命名空間:

xmlns:android_custom="https://schemas.android.com/apk/res/com.example.circlepregress"

拆解這一行:android_custom 是前綴(名稱可自取),後面的 https://schemas.android.com/apk/res/ 之後必須接你的應用程式包名。

差別在於:系統控制項寫 android:XXX="……",自定義控制項則寫 android_custom:XXX="……"。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:android_custom="https://schemas.android.com/apk/res/com.example.circlepregress"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.roundprogressbar.RoundProgressBar
        android:id="@+id/roundProgressBar2"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_alignLeft="@+id/roundProgressBar1"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="78dp"
        android_custom:roundColor="#D1D1D1"
        android_custom:roundProgressColor="@android:color/black"
        android_custom:textColor="#9A32CD"
        android_custom:textIsDisplayable="false"
        android_custom:roundWidth="10dip"
        android_custom:textSize="18sp"/>
</RelativeLayout>

幾個值得留意的實作細節

  • synchronized + postInvalidate() 的組合是重點。把 setter 標記為 synchronized 保護資料一致性,再用 postInvalidate() 而非 invalidate(),就能安全地從子執行緒更新進度。這也是「thread-safe 控制項」的標準寫法。
  • 整數除法陷阱。360 * progress / max 在 progress 與 max 皆為 int 時會做整數除法,這裡剛好是我們要的行為;但計算百分比時必須先轉 float,否則 progress < max 的情況下結果會恆為 0。
  • RectF 每次 onDraw 都 new 一個,會造成 GC 壓力。建議把它提升為成員變數,在 onSizeChanged() 或 onMeasure() 時計算一次即可。
  • 用 getWidth() 而非 getWidth()/getHeight() 取兩者。元件若不是正方形,圓會被壓扁。若要強制正圓,建議覆寫 onMeasure() 讓寬高取相同值。
  • setter 改完記得 invalidate()。範例中的 setCricleColor() 等方法改了值卻沒重繪,畫面不會即時更新,實務上請補上 postInvalidate()。

源碼下載:《Android 帶進度的圓形進度條》

以上就是本文的全部內容,希望對你的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved