編輯:關於 Android 程式設計
我們再用一個小實例,把「自定義 View + 自定義屬性」這套組合完整走一遍——這次要畫一個帶進度的圓形進度條。
先來看成果:

從上圖可以看到,我們可以自訂:圓環顏色、進度弧顏色、是否顯示百分比、百分比文字顏色與大小、圓環粗細,以及進度是空心(STROKE)還是實心(FILL)。變化相當多,接下來就一步步拆解。
定義各項屬性,不同屬性對應不同的 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。這個「一定要有預設值」的習慣能避免大量空值問題。
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; }
}
使用前,必須在佈局最上層宣告自定義屬性的命名空間:
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() 而非 invalidate(),就能安全地從子執行緒更新進度。這也是「thread-safe 控制項」的標準寫法。360 * progress / max 在 progress 與 max 皆為 int 時會做整數除法,這裡剛好是我們要的行為;但計算百分比時必須先轉 float,否則 progress < max 的情況下結果會恆為 0。onSizeChanged() 或 onMeasure() 時計算一次即可。onMeasure() 讓寬高取相同值。setCricleColor() 等方法改了值卻沒重繪,畫面不會即時更新,實務上請補上 postInvalidate()。源碼下載:《Android 帶進度的圓形進度條》
以上就是本文的全部內容,希望對你的學習有所幫助。
Android AsyncTask 源碼解析:從 execute 到 onPostExecute
一、概述 對做過 Android 的人來說,AsyncTask 是個老朋友。要跑一段耗時工作、跑完再把結果貼回介面上,它確實是一把順手的瑞士刀,也是 Thread + H
Android 學習筆記:用 Data 與 Type 讓系統自動挑選合適的 App 開啟檔案
仔細想想,手機上開啟一個檔案其實只有兩條路: 一是從檔案出發——檔案管理器知道副檔名,於是去找能處理這個類型的 App;二是從 App 出發——你在 Gallery 裡
FloatingActionButton 隨 RecyclerView 捲動淡入淡出的實作
先認識 Promoted Action Promoted Action 指的是一種「主要操作」按鈕,它不放在 ActionBar 裡,而是直接浮在可見的 UI 版面之上(
Android 安全機制解讀:進程、多用戶與文件權限模型
Android 的安全基石並非什麼黑科技,而是沿用了 Linux 的一套成熟機制:進程隔離、多用戶邊界,以及 UID/GID 加 rwx 權限位。理解了這三層,才能看懂後