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

Android 自訂元件實作指南(下):三種擴充策略

編輯:關於 Android 程式設計

一、Android 的元件模型

Android 提供了相當強大的 UI 元件模型,兩個基類是 View 與 ViewGroup。

內建的 Widget 包括 Button、TextView、EditText、ListView、CheckBox、RadioButton、Gallery、Spinner,以及 AutoCompleteTextView、ImageSwitcher、TextSwitcher 這類有特殊用途的元件。

可用的 Layout 則有 LinearLayout、FrameLayout、RelativeLayout、AbsoluteLayout,以及 API 14 以後(或 v7-support)才加入的 GridLayout。

二、自訂元件的基本三步

  1. 繼承 View 或其子類別。
  2. 覆寫父類的關鍵方法,如 onDraw()、onMeasure()、onLayout()。
  3. 在版面或程式碼中使用這個自訂類別。

三、完全自訂元件

最徹底的做法是直接繼承 View:

  1. 提供帶屬性參數的建構子,並視需要解析自訂屬性。
  2. 可在元件內部建立事件監聽器、屬性的 getter / setter 或其他行為。
  3. 幾乎一定要覆寫 onDraw() 與 onMeasure()——預設的 onDraw() 什麼都不畫,onMeasure() 則會給出一個 100×100 的尺寸。
  4. 視需要覆寫其他方法。

onDraw() 與 onMeasure() 的職責

onDraw(Canvas) 提供一個 Canvas,用來繪製 2D 圖形。若要做 3D,則應繼承 GLSurfaceView,可參考 api-demo 中的 GLSurfaceViewActivity。

onMeasure() 負責測量,有三個要點:

  1. 在需要知道寬高時被呼叫。
  2. 應計算出元件所需的寬高,並盡量落在傳入的規格範圍內。即使選擇超出,父 View 仍有最後決定權——它可以裁剪、捲動、拋出異常,或要求重新測量。
  3. 計算完成後必須呼叫 setMeasuredDimension(int width, int height),否則會拋出異常。

View 生命週期中可覆寫的方法

分類方法說明
建立建構子程式碼動態建立與 XML inflate 各有一個版本;後者必須解析並套用版面中的屬性。
建立onFinishInflate()View 與其所有子節點都 inflate 完成後呼叫。
版面onMeasure(int, int)決定自身與子節點的尺寸需求。
版面onLayout(boolean, int, int, int, int)為所有子節點指派位置與大小。
版面onSizeChanged(int, int, int, int)自身尺寸變動時呼叫。
繪製onDraw(Canvas)渲染自身內容。
事件onKeyDown / onKeyUp按鍵按下與放開。
事件onTrackballEvent(MotionEvent)軌跡球事件。
事件onTouchEvent(MotionEvent)觸控螢幕事件。
焦點onFocusChanged(boolean, int, Rect)取得或失去焦點。
焦點onWindowFocusChanged(boolean)所屬視窗取得或失去焦點。
附加onAttachedToWindow() / onDetachedFromWindow()附加與分離於視窗。
附加onWindowVisibilityChanged(int)所屬視窗的可見性變更。

範例:LabelView

api-demo 中的 LabelView 是最經典的入門範例:

package android.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

/**
 * 自訂 View 子類別的範例。LabelView 用來繪製單行文字,
 * 注意它不處理樣式化文字與由右至左的書寫系統。
 */
public class LabelView extends View {

    /** 手動 new 出來時使用這個建構子 */
    public LabelView(Context context) {
        super(context);
        initLabelView();
    }

    /**
     * 從版面檔 inflate 時使用這個建構子,
     * 屬性定義在 SDK/assets/res/any/classes.xml。
     */
    public LabelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();

        Resources.StyledAttributes a =
                context.obtainStyledAttributes(attrs, R.styleable.LabelView);

        CharSequence s = a.getString(R.styleable.LabelView_text);
        if (s != null) {
            setText(s.toString());
        }

        ColorStateList textColor = a.getColorList(R.styleable.LabelView_textColor);
        if (textColor != null) {
            setTextColor(textColor.getDefaultColor(0));
        }

        int textSize = a.getInt(R.styleable.LabelView_textSize, 0);
        if (textSize > 0) {
            setTextSize(textSize);
        }

        a.recycle();
    }

    private void initLabelView() {
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16);
        mTextPaint.setColor(0xFF000000);

        mPaddingLeft = 3;
        mPaddingTop = 3;
        mPaddingRight = 3;
        mPaddingBottom = 3;
    }

    /** 設定要顯示的文字 */
    public void setText(String text) {
        mText = text;
        requestLayout();
        invalidate();
    }

    /** 設定文字大小 */
    public void setTextSize(int size) {
        mTextPaint.setTextSize(size);
        requestLayout();
        invalidate();
    }

    /** 設定文字顏色 */
    public void setTextColor(int color) {
        mTextPaint.setColor(color);
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),
                             measureHeight(heightMeasureSpec));
    }

    /** 依 measureSpec 的限制計算寬度 */
    private int measureWidth(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;              // 父層已指定大小
        } else {
            result = (int) mTextPaint.measureText(mText)
                     + mPaddingLeft + mPaddingRight;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    /** 依 measureSpec 的限制計算高度 */
    private int measureHeight(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        mAscent = (int) mTextPaint.ascent();

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            // 注意 ascent 是負數
            result = (int) (-mAscent + mTextPaint.descent())
                     + mPaddingTop + mPaddingBottom;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(mText, mPaddingLeft, mPaddingTop - mAscent, mTextPaint);
    }

    private Paint mTextPaint;
    private String mText;
    private int mAscent;
}

對應的版面配置,用自訂命名空間傳入屬性:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res/com.example.android.apis"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.example.android.apis.view.LabelView
        android:background="@drawable/red"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:text="Red" />

    <com.example.android.apis.view.LabelView
        android:background="@drawable/blue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:text="Blue"
        app:textsize="20dp" />

    <com.example.android.apis.view.LabelView
        android:background="@drawable/green"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:text="Green"
        app:textcolor="#ffffffff" />

</LinearLayout>

這個範例示範了五件事:繼承 View 的完全自訂、帶屬性參數的建構子與自訂屬性(R.styleable.LabelView)、標準的 public setter、以 measureWidth / measureHeight 拆解 onMeasure(),以及用 onDraw() 把內容畫到 Canvas 上。

特別留意 setText() 與 setTextSize() 中同時呼叫了 requestLayout() 與 invalidate():前者觸發重新測量與配置(尺寸可能變),後者觸發重繪。只改顏色時尺寸不變,所以 setTextColor() 只呼叫 invalidate() 就够了——這個區別能省下不少不必要的版面計算。

四、組合元件(Compound Component)

把現成的元件組合起來,形成一個新元件。做法:

  1. 建立一個類別,繼承某個 Layout 或 ViewGroup。
  2. 在建構子中先呼叫父類建構子,然後把需要的子元件組裝進來;同樣支援自訂屬性。
  3. 視需要建立監聽器處理各項互動。
  4. 提供屬性的 getter / setter。
  5. 若繼承的是 Layout 類別,通常不需要覆寫 onDraw() 與 onMeasure(),因為父類已有預設行為。
  6. 視需要覆寫其他 onXxx() 方法。

api-demo 的 List4 與 List6 內部類別 SpeechView 就是範例(以下為 List6 版本):

private class SpeechView extends LinearLayout {

    public SpeechView(Context context, String title, String dialogue, boolean expanded) {
        super(context);
        this.setOrientation(VERTICAL);

        // 這裡用程式碼組建子 View,也可以改寫在 XML 中
        mTitle = new TextView(context);
        mTitle.setText(title);
        addView(mTitle, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        mDialogue = new TextView(context);
        mDialogue.setText(dialogue);
        addView(mDialogue, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        mDialogue.setVisibility(expanded ? VISIBLE : GONE);
    }

    /** 設定標題 */
    public void setTitle(String title) {
        mTitle.setText(title);
    }

    /** 設定對話內容 */
    public void setDialogue(String words) {
        mDialogue.setText(words);
    }

    /** 展開或收合對話(List4 中沒有這個方法) */
    public void setExpanded(boolean expanded) {
        mDialogue.setVisibility(expanded ? VISIBLE : GONE);
    }

    private TextView mTitle;
    private TextView mDialogue;
}

它繼承 LinearLayout 做縱向排列,內含標題與內容兩個 TextView。List4 永遠展開兩者;List6 則可以點標題來收合或展開內容。

五、擴充既有 View 型別

第三種策略是繼承既有 View 並增強其功能。SDK 中的記事本 NotePad 範例裡,NoteEditor.LinedEditText 就是擴充 EditText 的示範:

public static class LinedEditText extends EditText {

    private Rect mRect;
    private Paint mPaint;

    /** LayoutInflater 會使用這個建構子 */
    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(0x800000FF);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 取得文字的行數(EditText 繼承自 TextView)
        int count = getLineCount();

        Rect r = mRect;
        Paint paint = mPaint;

        // 每一行文字畫一條底線
        for (int i = 0; i < count; i++) {
            // 取得該行的範圍座標,回傳值為 y 方向的基線位置
            int baseline = getLineBounds(i, r);

            // 從矩形左端畫到右端,位置在基線下方 1 個像素
            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        }

        // 最後一定要呼叫父類實作
        super.onDraw(canvas);
    }
}

定義方式:宣告為 public static 內部類別,外部可用 NoteEditor.LinedEditText 存取。加上 static 表示它不依賴外部類別的成員,避免產生非必要的「合成方法」。

建構子:先呼叫父類建構子,且採用帶屬性參數的版本,因為它是從 XML inflate 出來的。

覆寫的方法:只有 onDraw()。在每行文字的基線下方 1 像素處畫一條藍線,寬度等於該行寬度,最後呼叫 super.onDraw()。

在版面中使用:用完全限定類名搭配 $ 引用內部類別。

<view xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/note"
    android:background="@android:color/transparent"
    android:capitalize="sentences"
    android:fadingedge="vertical"
    android:gravity="top"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:scrollbars="vertical"
    android:textSize="22sp"
    class="com.example.android.notepad.NoteEditor$LinedEditText" />

六、三種策略怎麼選

判斷很簡單:需要全新外觀與互動就走完全自訂,繼承 View 或 ViewGroup;只是把既有元件湊成一個區塊就用組合元件,繼承 Layout,省掉自己處理測量的麻煩;只想在既有元件上加一點細節(畫底線、加驗證、改繪製行為)就繼承該元件並覆寫單一方法,成本最低。

實務上第三種最常見也最划算,第一種則要付出最多的測量與繪製成本。一開始先問「能不能用組合解決」,往往比直接衝去自繪更有效率。

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