編輯:關於 Android 開發
本文從零打造一個自訂控制項:外圈一個圓框,內部一個扇形隨時間增長,最終形成一個圓環進度條。這個練習幾乎涵蓋了自訂 View 的所有關鍵環節。

整體分為幾個決策點:
繼承 View 而非 ViewGroup。因為我們要完全自己畫,沒有子元件。
必須重寫兩參數建構子。只有這個建構子會帶入 AttributeSet——也就是 XML 中寫的那些自訂屬性。少了它,在版面檔中使用會直接崩潰。
哪些屬性該開放給使用者?本範例開放五項:圓框顏色、扇形顏色、起始角度、增長步長、內間距。
在 res/values 下建立 attrs.xml(名稱可自訂,但業界慣例如此):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ProgressView">
<!-- circleColor 設定圓形邊框的顏色
sweepColor 設定扇形變換的顏色
startAngle 設定起始角度
sweepStep 設定變換的步長 -->
<attr name="circleColor" format="color|reference"></attr>
<attr name="sweepColor" format="color|reference"></attr>
<attr name="startAngle" format="integer"></attr>
<attr name="sweepStep" format="integer"></attr>
<attr name="padding" format="integer"></attr>
</declare-styleable>
</resources>
幾個關鍵點:<declare-styleable> 的 name 屬性會成為 R.styleable 中的類別名稱,用於後續讀取 AttributeSet。<attr> 的 name 則是實際的屬性名。而 format 宣告了這個屬性接受哪一類值——color|reference 代表可以寫 #FF0000 也可以寫 @color/red,用 | 串接多種型別是常見做法。
package com.yztc.customprogressview;
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.util.AttributeSet;
import android.view.View;
/**
* 自訂的圓形進度控制項
*/
public class ProgressView extends View {
private int sweepStep = 10; // 扇形變換的步長(角度)
private int padding = 40; // 外框距離扇形的間距
private int circleColor = Color.GRAY; // 邊框顏色
private int sweepColor = Color.BLUE; // 扇形顏色
private int startAngle = 90; // 起始角度
private int storke = 20; // 外框粗細
private int sweepAngle = 0; // 已掃過的角度
private static final int DEFAULT_WIDTH = 200;
private static final int DEFAULT_HEIGHT = 200;
public ProgressView(Context context) {
super(context);
}
/**
* 若要在 XML 中使用該自訂控制項,則必須重寫兩參數的建構子
* 因為使用自訂屬性時,系統會預設傳遞一個 AttributeSet 進來
*/
public ProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ProgressView);
if (array != null) {
// 取得我們在 XML 中設定的各個自訂屬性
sweepStep = array.getInteger(R.styleable.ProgressView_sweepStep, sweepStep);
padding = array.getInteger(R.styleable.ProgressView_padding, padding);
circleColor = array.getColor(R.styleable.ProgressView_circleColor, circleColor);
sweepColor = array.getColor(R.styleable.ProgressView_sweepColor, sweepColor);
startAngle = array.getInteger(R.styleable.ProgressView_startAngle, startAngle);
// 回收 TypedArray 資源
array.recycle();
}
}
/**
* 先繪製外框,再繪製內部扇形
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
Paint mPaint = new Paint();
mPaint.setAntiAlias(true); // 設定抗鋸齒
// 繪製外層圓框
mPaint.setColor(circleColor);
mPaint.setStrokeWidth(storke);
mPaint.setStyle(Paint.Style.STROKE); // 設定為空心圓
// 依 getWidth() 決定圓心位置,繪製外層圓
canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2 - storke / 2, mPaint);
invalidate(); // 請求重新繪製
// 繪製內部的扇形
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(sweepColor);
/*
drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)
RectF oval 指定扇形的矩形容器,即圓弧的外輪廓矩形
float startAngle 圓弧的起始角度
float sweepAngle 圓弧掃過的角度(順時針方向)
boolean useCenter 設為 true 時將圓心包括在內,即成扇形;false 則只畫弧線
Paint paint 畫筆:顏色、填充樣式
RectF(float left, float top, float right, float bottom)
left 矩形左邊點(左切點)的 x 座標
top 矩形上邊點(上切點)的 y 座標
right 矩形右邊點(右切點)的 x 座標
bottom 矩形下邊點(下切點)的 y 座標
*/
// RectF 的四個參數對應其內切圓的四個切點座標
RectF rectF = new RectF(
padding + storke, padding + storke,
getWidth() - padding - storke, getWidth() - padding - storke);
canvas.drawArc(rectF, startAngle, sweepAngle, true, mPaint);
// 依步長更新已掃過的角度
sweepAngle += sweepStep;
sweepAngle = sweepAngle > 360 ? 0 : sweepAngle;
invalidate(); // 重繪 view
}
/**
* 因為是繼承 View 自訂的,所以 onMeasure() 必須重寫
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int wSize = MeasureSpec.getSize(widthMeasureSpec);
int hSize = MeasureSpec.getSize(heightMeasureSpec);
// 因為繪製的是圓,判斷寬或高中的一個即可
switch (wMode) {
case MeasureSpec.AT_MOST: // android:layout_width="wrap_content"
// 取得螢幕像素密度
float density = getResources().getDisplayMetrics().density;
wSize = (int) (DEFAULT_WIDTH * density);
hSize = (int) (DEFAULT_HEIGHT * density);
break;
case MeasureSpec.EXACTLY: // match_parent 或指定數值
wSize = hSize = Math.min(wSize, hSize);
break;
}
// 只要重寫 onMeasure(),一定要呼叫此方法,否則會報錯
setMeasuredDimension(wSize, hSize);
}
}
圓心與半徑。因為是圓,getWidth()/2 就是圓心。半徑要減去 storke/2,是為了讓粗邊框完整落在 View 範圍內而不被裁切。
扇形的 RectF 怎麼算。左邊點 = 邊框寬度 + 內間距;右邊點 = 總寬度 − 邊框寬度 − 內間距。上下同理。畫一張草圖立刻就懂——本質上就是「外框往內縮 padding」。
drawCircle 的半徑陷阱。Canvas 的 drawCircle 實際畫出的邊界是「你指定的半徑 + 一半的 strokewidth」。所以若 radius=50、strokeWidth=10,視覺上的外緣其實在 55。忽略這點會導致扇形與外框的切點位置對不上,看起來像有鋸齒。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.yztc.customprogressview.MainActivity">
<com.yztc.customprogressview.ProgressView
android:id="@+id/pv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
app:padding="20"
app:circleColor="#aa0000"
app:sweepColor="#00aa00"
app:sweepStep="1"
app:startAngle="180" />
</RelativeLayout>
根節點底下這行是關鍵,不能漏:
xmlns:app="https://schemas.android.com/apk/res-auto"
它宣告了 app 這個命名空間,之後才能用 app:你的屬性名 指定自訂屬性。這個 app 前綴可以換名字,只要與 xmlns 後面的識別字一致即可。

範例的重點是示範原理,但仍有幾處不建議照抄:
不要在 onDraw 裡呼叫 invalidate。範例在 onDraw 中呼叫了兩次 invalidate,等於形成無限重繪迴圈,CPU 會持續滿載、電量狂掉。正確做法是把角度遞增的邏輯移到獨立的計時器或 ValueAnimator 中,onDraw 只負責「照目前狀態畫出來」,保持純粹。
Paint 應該往上提。每次 onDraw 都 new 一個 Paint 會造成大量 GC。應宣告為類別成員,在初始化時建立一次即可。
onMeasure 沒處理 UNSPECIFIED。在 ScrollView 等容器中可能遇到這個模式,缺少對應分支會導致尺寸計算異常。
沒有提供外部設定進度的 API。作為一個「Progress」控制項,應該有 setProgress(int) 方法讓外部指定進度百分比,而不是靠內部計時器自己跑。這樣才能真正被業務邏輯驅動。
wrap_content 的處理太粗糙。範例直接用固定常數乘 density,較嚴謹的做法是依 padding 與 stroke 反推內容尺寸。
整體而言,這個範例把自訂 View 的三個核心方法——attrs 宣告屬性、onMeasure 決定尺寸、onDraw 負責繪製——都完整走過一遍了。把這三件事理解透,之後再自訂任何控制項都只是同一套流程的變形。
打造懸浮對話框:從底部彈出的 Dialog 實現
直接看代碼 懸浮對話框(從屏幕底部彈出的 Dialog)在很多應用裡都很常見,比如選擇城市、選擇操作項等。下面直接上代碼: private void setDialog
Android 自定義倒數計時 TextView:列表項中的剩餘時間顯示
Android 自定義倒數計時 TextView:列表項中的剩餘時間顯示 在音樂或音頻列表頁面中,常需要在播放時顯示剩餘時間,暫停時則停止倒數。若使用 ListView,
手機衛士黑名單實作:ListView 結合 SQLite 的增刪改
手機衛士的黑名單功能,本質上是「列表介面 + 本地資料庫」的組合練習。使用者可以在列表中加入號碼與攔截模式,也能刪除既有記錄。新增與刪除新增時可透過自訂對話框輸入號碼與模
Android 文字與輸入服務指南:剪貼簿、複製貼上與輸入法整合
Android 文字與輸入服務指南 Android 的文字服務包含剪貼簿、複製貼上、拼字檢查與輸入法。開發者可運用系統服務提升操作便利性,也可實作自訂輸入法、字典或拼字檢