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

Android 自定義 View 入門:常用回調函數與第一個自繪控制項

編輯:關於 Android 程式設計

自定義 View 必須熟悉的回調

自繪控制項的本質,就是接管 View 生命週期中的幾個關鍵節點。下面這些方法值得反覆看:

  • onFinishInflate():View 中所有子控制項都已從 XML 映射完成後觸發。
  • onMeasure(int, int):決定自己以及所有子元素的大小。
  • onLayout(boolean, int, int, int, int):為所有子元素分配位置與尺寸時觸發。
  • onSizeChanged(int, int, int, int):View 尺寸發生變化時觸發。
  • onDraw(Canvas):真正把內容畫出來的細節所在。
  • onKeyDown / onKeyUp:按鍵按下與彈起。
  • onTrackballEvent(MotionEvent):軌跡球事件。
  • onTouchEvent(MotionEvent):觸屏事件。
  • onFocusChanged(boolean, int, Rect):取得或失去焦點時觸發。
  • onWindowFocusChanged(boolean):所處窗口取得或失去焦點時觸發。
  • onAttachedToWindow():被掛載到窗口時觸發。
  • onDetachedFromWindow():從窗口移除時觸發,與上一個相反,是釋放資源的關鍵位置。
  • onWindowVisibilityChanged(int):窗口內可見性發生變化時觸發。

第一步:繼承 View,重寫需要的方法

下面這個例子畫一個紅色圓點,並讓它跟著手指移動——這是最小的自定義 View 骨架。

package sn.dolp.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class XmlView extends View {

    private float cx = 40;
    private float cy = 50;
    private final Paint paint = new Paint();

    // 代碼創建時使用
    public XmlView(Context context) {
        super(context);
    }

    // 從 XML 加載時使用,自定義 View 少了這個構造函數會直接崩潰
    public XmlView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public XmlView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.RED);
        canvas.drawCircle(cx, cy, 15, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        cx = event.getX();
        cy = event.getY();
        invalidate();   // 請求重繪,onDraw 會被再次呼叫
        return true;    // 表示事件已被消費
    }
}

第二步:在布局中引用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    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="sn.dolp.view.MainActivity">

    <!-- 使用全限定類名插入自定義 View -->
    <sn.dolp.view.XmlView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

幾個容易踩到的坑

  • 務必提供 (Context, AttributeSet) 構造函數。從 XML 加載時系統只會呼叫這一個,缺了就拋 NoSuchMethodException。
  • onDraw 裡不要建立對象。Paint、Path、Rect 這類對象請提到成員變數,否則每幀都在配置記憶體,滑動時會明顯掉幀。
  • 記得呼叫 super.onDraw()。背景與部分默認繪製依賴它。
  • invalidate 與 postInvalidate 的區別。前者只能在 UI 執行緒呼叫,後者可在子執行緒使用。
  • 自定義屬性更友好。把顏色、半徑、文字抽成 res/values/attrs.xml 中的 declare-styleable,再用 (Context, AttributeSet) 裡的 TypedArray 讀取,這樣控制項才能像系統控制項一樣在 XML 裡配置。
  • wrap_content 要自己處理。如果沒有重寫 onMeasure,自定義 View 在 wrap_content 下往往會變成期望外的尺寸,建議依實際內容自行計算並回傳 AT_MOST 規格。

參考來源:qingdujun 的原文,以及 UUTON 的相關文章。

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