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

Android 自定義時鐘控件:onMeasure、onDraw 與定時刷新

編輯:關於 Android 程式設計

自定義 View 是 Android 的必備技能,而時鐘是個特別合適的練習題——它同時涵蓋了自定義屬性、View 測量、Canvas 繪製、線程定時刷新幾個知識點。本文記錄一個完整實現,並順手演示如何擴展已有的系統控件。

一、自定義時鐘 MyClock

1.1 定義自定義屬性

先在 values/attrs.xml 中聲明:

<resources>
    <declare-styleable name="MyClock">
        <attr format="color" name="circleColor01" />
        <attr format="color" name="circleColor02" />
        <attr format="dimension" name="circleWidth" />
    </declare-styleable>

    <declare-styleable name="Textview">
        <attr format="color" name="lineColor" />
        <attr format="dimension" name="lineWidth" />
    </declare-styleable>
</resources>

這裡有個實用約定:讀取屬性時,TypedArray 的引用名是「declare-styleable 的 name + 下劃線 + 屬性名」,例如 R.styleable.MyClock_circleColor01。記住這個規則就不會寫錯常量名。

1.2 Java 實現

public class MyClock extends View {

    private int hour, minute, second;
    private boolean running;

    // circlePaint 畫圓、linePaint 畫刻度、timerPaint 畫時分秒針、numPaint 畫數字
    private Paint circlePaint, linePaint, timerPaint, numPaint;

    private int circleColor01, circleColor02;   // 外圈與內圈顏色
    private int circleWidth;                    // 時鐘外圈寬度
    private Handler handler;
    private float density = getResources().getDisplayMetrics().density;

    public MyClock(Context context) {
        super(context);
        circleColor01 = 0xFFFF0000;
        circleColor02 = 0xFFFFFFFF;
        circleWidth = (int) (4 * density);
        init();
    }

    public MyClock(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyClock);
        circleColor01 = a.getColor(R.styleable.MyClock_circleColor01, 0xFFFF0000);
        circleColor02 = a.getColor(R.styleable.MyClock_circleColor02, 0xFFFFFFFF);
        circleWidth = a.getDimensionPixelOffset(R.styleable.MyClock_circleWidth, 4);
        init();
        a.recycle();    // 用完務必回收
    }

    private final void init() {
        hour = 0; minute = 0; second = 0;
        running = false;
        handler = new Handler();

        circlePaint = new Paint();
        circlePaint.setAntiAlias(true);

        linePaint = new Paint();
        linePaint.setColor(0xFF000000);
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(2.0f * density);

        timerPaint = new Paint();
        timerPaint.setColor(0xFF000000);
        timerPaint.setAntiAlias(true);
        timerPaint.setStrokeWidth(3.0f * density);

        numPaint = new Paint();
        numPaint.setColor(0xFF000000);
        numPaint.setAntiAlias(true);
        numPaint.setTextSize(40);
        numPaint.setStrokeWidth(3.0f * density);
    }
}

注意所有尺寸都乘以 density,這樣在不同分辨率設備上視覺比例才一致。直接寫像素值會在高密度屏上小到看不見。

1.3 重寫 onMeasure:讓時鐘保持正圓

時鐘必須是圓的,所以寬高要取兩者中的較小值:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = measureWidth(widthMeasureSpec);
    int height = measureHeight(heightMeasureSpec);
    int result = Math.min(width, height);
    setMeasuredDimension(result, result);
}

private int measureWidth(int measureSpec) {
    int result;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    if (specMode == MeasureSpec.EXACTLY || specMode == MeasureSpec.AT_MOST) {
        result = specSize;
    } else {
        result = 256;       // 未指定時給個默認值
    }
    return result;
}

private int measureHeight(int measureSpec) {
    // 同上
    return measureWidth(measureSpec);
}

EXACTLY 對應 xml 中寫具體數值,AT_MOST 對應 match_parent 或 wrap_content,這兩種情況直接採用測量值;其他情況給個兜底默認值,避免尺寸為 0 導致無法繪製。

1.4 重寫 onDraw:表盤、刻度、指針

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

    float cx = this.getWidth() / 2f;
    float cy = this.getHeight() / 2f;
    float radius = this.getWidth() / 2f;

    // 1. 外圈(稍大的圓)+ 內圈(留出 circleWidth 的邊)
    circlePaint.setColor(0xFF0000FF);
    canvas.drawCircle(cx, cy, radius, circlePaint);
    circlePaint.setColor(circleColor02);
    canvas.drawCircle(cx, cy, radius - circleWidth, circlePaint);

    // 2. 十二個大刻度與數字
    for (int i = 1; i <= 12; i++) {
        canvas.save();
        canvas.rotate(30 * i, cx, cy);
        canvas.drawLine(cx, 25 * density, cx, circleWidth + 1 * density, linePaint);
        canvas.drawText("" + i, cx, 20 * density + 65, numPaint);
        canvas.restore();
    }

    // 3. 六十個小刻度
    for (int i = 1; i <= 60; i++) {
        canvas.save();
        canvas.rotate(6 * i, cx, cy);
        canvas.drawLine(cx, 15 * density, cx, circleWidth + 1 * density, linePaint);
        canvas.restore();
    }

    // 4. 時針:一小時 30 度,一分鐘額外偏移 0.5 度
    canvas.save();
    canvas.rotate(hour * 30 + minute / 2f, cx, cy);
    timerPaint.setStrokeWidth(5.0f * density);
    canvas.drawLine(cx, cy, cx, cy - (radius / 10 - circleWidth) * density, timerPaint);
    canvas.restore();

    // 5. 分針:一分鐘 6 度
    canvas.save();
    canvas.rotate(minute * 6, cx, cy);
    timerPaint.setStrokeWidth(4.0f * density);
    canvas.drawLine(cx, cy, cx, cy - (radius / 8 - circleWidth) * density, timerPaint);
    canvas.restore();

    // 6. 秒針:一秒鐘 6 度
    canvas.save();
    canvas.rotate(second * 6, cx, cy);
    timerPaint.setStrokeWidth(3.0f * density);
    canvas.drawLine(cx, cy, cx, cy - (radius / 7 - circleWidth) * density, timerPaint);
    canvas.restore();
}

這段代碼的關鍵技巧是 「畫一條固定方向的線,再用 canvas.rotate 整體旋轉」。所有指針都從 12 點方向出發,通過旋轉角度定位,比用三角函數算端點坐標簡單得多。

角度換算關係值得記住:

* 時針:每小時 30°(360/12),並且要加上分針帶來的細微偏移 minute / 2,這樣時針才會隨分針平滑移動
* 分針、秒針:每單位 6°(360/60)

另外注意每個 rotate 都配對了 save() 與 restore()。少了 restore,畫布矩陣會被污染,後續繪製全部錯位——這是 Canvas 繪製最常見的錯誤之一。

1.5 定時刷新

用一個內部 Runnable 每秒讀取系統時間並刷新:

private class TimerTask implements Runnable {
    public void run() {
        while (running) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                return;
            }
            Calendar c = Calendar.getInstance();
            hour = c.get(Calendar.HOUR);
            minute = c.get(Calendar.MINUTE);
            second = c.get(Calendar.SECOND);

            // 中斷線程不安全,必須切回主線程調用 invalidate
            handler.post(new Runnable() {
                public void run() {
                    MyClock.this.invalidate();
                }
            });
        }
    }
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    start();
}

@Override
protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    stop();
}

public void start() {
    if (!running) {
        running = true;
        new Thread(new TimerTask()).start();
    }
}

public void stop() {
    running = false;
}

把 start()/stop() 掛在 onAttachedToWindow 與 onDetachedFromWindow 上,是個值得沿用的習慣——控件一旦從窗口移除,線程立刻停止,不會洩漏。

二、擴展已有控件:給 TextView 加下劃線

自定義 View 不只是從零繼承 View,更常見的是擴展系統控件。這裡寫一個自帶下劃線的 Textview:

public class Textview extends TextView {

    private int lineColor;
    private int lineWidth;
    private Paint linePaint;

    public Textview(Context context) {
        super(context);
        lineColor = 0xFF000000;
        lineWidth = 2;
        init();
    }

    public Textview(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Textview);
        lineColor = a.getColor(R.styleable.Textview_lineColor, 0xFF000000);
        lineWidth = a.getDimensionPixelOffset(R.styleable.Textview_lineWidth, 2);
        init();
        a.recycle();
    }

    private final void init() {
        linePaint = new Paint();
        linePaint.setColor(lineColor);
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(lineWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);   // 關鍵:先讓原控件畫完自己
        // 再在底部補一條線
        canvas.drawLine(0, this.getHeight(), this.getWidth(), this.getHeight(), linePaint);
    }
}

這裡最重要的是 super.onDraw(canvas) 的位置。必須先調用父類實現把文字畫出來,再畫裝飾性的線,否則線會蓋住文字。這個「先 super 再裝飾」的模式,是所有擴展型自定義控件的通用套路。

三、佈局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <!-- 用全包名引用自定義控件,自定義屬性通過 app 命名空間傳入 -->
    <com.rj141.sb.myclockview.Textview
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/clock"
        android:textSize="24dp"
        app:lineColor="#FFFF0000"
        app:lineWidth="3dp" />

    <com.rj141.sb.myclockview.MyClock
        android:id="@+id/id_clock"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        app:circleColor01="#FF0000FF"
        app:circleColor02="#ffffff"
        app:circleWidth="4dp">

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:orientation="horizontal">

            <Button
                android:id="@+id/start"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:text="@string/start" />

            <Button
                android:id="@+id/stop"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:text="@string/stop" />
        </LinearLayout>
    </com.rj141.sb.myclockview.MyClock>
</LinearLayout>

自定義屬性使用 app: 命名空間(頭部需聲明 xmlns:app="https://schemas.android.com/apk/res-auto"),標籤名寫完整包名。

四、Activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button start, stop;
    private MyClock myClock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myClock = findViewById(R.id.id_clock);
        start = findViewById(R.id.start);
        start.setOnClickListener(this);
        stop = findViewById(R.id.stop);
        stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                myClock.start();
                break;
            case R.id.stop:
                myClock.stop();
                break;
            default:
                break;
        }
    }
}

最終效果:

五、要點回顧

1. 自定義屬性三步走——attrs.xml 聲明 declare-styleable、構造方法中 obtainStyledAttributes 讀取、用完 recycle。
2. onMeasure 決定尺寸——正圓形控件取寬高最小值,並記得處理非 EXACTLY 的兜底情況。
3. onDraw 用 save/rotate/restore 畫指針——固定方向畫線再旋轉,比三角函數簡單,但 save/restore 必須配對。
4. 擴展型控件先調 super.onDraw——保證原有內容先畫,裝飾後畫。
5. 線程綁定生命週期——onAttachedToWindow 啟動、onDetachedFromWindow 停止,invalidate 必須回主線程調用。

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