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

Android 自定義 View 實戰:從繪製流程到屬性封裝的完整路線

編輯:關於 Android 程式設計

Android 為開發者準備了大量現成的 UI 元件——TextView、Button、ImageView,再加上 LinearLayout、RelativeLayout 這些布局容器,用它們拼出的介面往往已經足夠漂亮。但在真實專案裡,設計稿常常不按套路出牌:一個造型特殊的圓角頭像、一組自家產品獨有的圖表、一個帶呼吸效果的按鈕。這時候與其層層嵌套硬湊,不如自己動手寫一個 View。

想寫好自定義 View,先得弄清楚它站在怎樣的繼承體系裡,以及系統究竟是如何把它一步步畫到螢幕上的。

一、先認識 View 體系

Android 中所有可見的介面元素,本質上都是 View 與 ViewGroup 構成的樹形結構。View 負責在螢幕上繪製可與使用者互動的內容;ViewGroup 則充當容器,裝下其他 View(也可以是另一個 ViewGroup),一層層嵌套出完整畫面。

系統提供的各類子類,已經覆蓋了常用輸入元件與主流布局方式。而自定義 View,就是要在這棵既有的樹上,長出屬於自己的一枝。

二、五個關鍵環節:View 的繪製流程

一個 View 從被建立到真正呈現在使用者眼前,會依序走過下面幾步:

  1. 建構函數:初始化的起點,也是讀取自定義屬性的地方。
  2. onMeasure:測量,決定這個 View 究竟要多寬多高。
  3. onSizeChanged:尺寸最終確定後的回调,適合做與長寬相關的運算。
  4. onLayout:確定自身(以及子 View)在父容器中的位置。
  5. onDraw:真正動筆,把內容畫到 Canvas 上。

走完 onDraw 之後並不是終點,而是一個閉環:只要 View 的內部狀態改變並呼叫 invalidate(),流程便會重新開始,畫面隨之刷新。所有自定義動畫的原理,都在這一行呼叫裡。

一句話記住主線:Constructor → onMeasure → onSizeChanged → onLayout → onDraw,狀態變化時經由 invalidate 回到重繪。

三、透過建構函數引入自定義屬性

自定義 View 通常要重寫三個建構函數,其中帶 AttributeSet 的那個最為關鍵——XML 裡寫下的屬性,就是從這裡送進來的。

public CustomView(Context context) {
    super(context);
}

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

接著在 res/values 目錄下建立 attrs.xml,用 declare-styleable 宣告一組屬於自己的屬性:

<resources>
    <declare-styleable name="CircleImageView">
        <attr name="border_color" format="color" />
        <attr name="border_width" format="dimension" />
    </declare-styleable>
</resources>

使用前,記得在布局檔的根節點宣告命名空間:

xmlns:app="https://schemas.android.com/apk/res-auto"

於是就能在 XML 裡像使用系統屬性一樣使用它們:

<com.bm.dylan.view.CircleImageView
    android:id="@+id/civ_personal_information_head"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:src="@mipmap/personalcenter_head"
    app:border_color="@color/white"
    app:border_width="2dp" />

最後在建構函數中用 TypedArray 把值取出來。這裡有個容易忽略的細節:用完記得呼叫 recycle(),否則會造成資源不必要的佔用。

public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray a = context.obtainStyledAttributes(
            attrs, R.styleable.CircleImageView, defStyle, 0);
    int borderWidth = a.getDimensionPixelSize(
            R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
    int borderColor = a.getColor(
            R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);
    a.recycle();
}

format 支援的型別相當豐富,常用的有以下幾種:

型別format 值XML 中的寫法示例
資源引用referenceapp:name="@string/label"
顏色colorapp:textColor="#ff0000"
布林值booleanapp:isVisible="false"
尺寸dimensionapp:myWidth="100dp"
浮點數floatapp:fromAlpha="0.3"
整數integerapp:framesCount="22"
字串stringapp:title="我的標題"
百分比fractionapp:pivotX="200%"
列舉enumapp:borderRadius="circle"
位運算flagandroid:windowSoftInputMode="stateUnspecified|adjustPan"
混合型別colorapp:background="@drawable/bg|#00FF00"

四、測量尺寸:onMeasure 與 MeasureSpec

onMeasure 的兩個參數看起來像是寬和高,其實並不是。它們是由「尺寸」與「測量模式」打包而成的 32 位整數,需要透過 MeasureSpec 拆開來讀。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int w = getMeasureWidth(widthMeasureSpec);
    int h = getMeasureHeight(heightMeasureSpec);
    // 必須呼叫,否則會拋出異常
    setMeasuredDimension(w, h);
}

private int getMeasureWidth(int widthMeasureSpec) {
    int result = 0;
    int size = MeasureSpec.getSize(widthMeasureSpec);
    int mode = MeasureSpec.getMode(widthMeasureSpec);
    if (mode == MeasureSpec.EXACTLY) {
        result = size;
    } else if (mode == MeasureSpec.AT_MOST) {
        result = Math.min(result, size);
    } else {
        result = (int) paint.measureText("") + getPaddingLeft() + getPaddingRight();
    }
    return result;
}

三種測量模式的含義如下:

模式說明
UNSPECIFIED父容器不給任何限制,子 View 想多大就多大,多見於 ScrollView 之類的容器。
EXACTLY父容器已經明確指定了尺寸,對應 match_parent 或寫死的 dp 值。
AT_MOST子 View 大小不超過上限,上限通常就是父容器可用空間,對應 wrap_content。

換句話說,重寫 onMeasure 的最終目的只有一個:算出自己的寬高,並交給 setMeasuredDimension 保存起來。

五、尺寸確定:onSizeChanged

View 的大小不只取決於自己,還受父容器擺布,因此凡是與最終尺寸相關的初始化,最好都放進系統提供的 onSizeChanged 裡。它有四個參數:新寬、新高、舊寬、舊高。

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    // 在這裡計算半徑、中心點等依賴尺寸的數值
}

六、擺放位置:onLayout

onLayout 決定的是位置而非大小。單純繼承 View 時通常不需要關心它,但一旦自己寫 ViewGroup,這一步就必須實作:一般做法是遍歷所有子 View,逐一算出座標,再呼叫 layout 落位。

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int mTotalHeight = 0;
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        int measuredWidth = childView.getMeasuredWidth();
        int measureHeight = childView.getMeasuredHeight();
        childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight + measureHeight);
        mTotalHeight += measureHeight;
    }
}

四個參數分別對應一組取用方法:l 是左側距父容器左緣的距離(getLeft)、t 是頂部距離(getTop)、r 是右側距離(getRight)、b 是底部距離(getBottom)。

七、真正動筆:onDraw

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 剩下的交給 Canvas
}

八、繪圖基礎:Canvas 與 Paint

Canvas 是畫布,負責「畫什麼形狀」;Paint 是畫筆,負責「用什麼樣式畫」。兩者搭配,幾乎能畫出任何東西。

Canvas 的常用繪製方法:

canvas.drawLine(startX, startY, stopX, stopY, paint);   // 直線
canvas.drawRect(left, top, right, bottom, paint);      // 矩形
canvas.drawCircle(cx, cy, radius, paint);              // 圓形
canvas.drawText(text, x, y, paint);                    // 文字
canvas.drawBitmap(bitmap, left, top, paint);           // 圖片
canvas.drawArc(rectF, startAngle, sweepAngle, useCenter, paint); // 弧線

Paint 的常用屬性設定:

setAntiAlias(true);   // 抗鋸齒
setColor(color);      // 顏色
setARGB(a, r, g, b);  // 分別指定四通道
setAlpha(alpha);      // 透明度
setTextSize(size);    // 字級
setStyle(Paint.Style.FILL);  // 空心或實心
setStrokeWidth(width);       // 描邊寬度

九、對外暴露操作與回调

自定義 View 寫完之後,通常還需要一組對外方法,讓外部能控制它的狀態,或者反过来通知外部發生了什麼。Button 的點擊事件就是這個思路:內部攔截手勢,外部註冊監聽。自定義 View 也一樣,開一個 setProgress()、setStyle(),或者定義一個 OnXxxListener 介面,元件才真正好用。

十、自定義 View 的三種常見流派

  1. 擴展现有元件:例如繼承 ImageView 做圓形頭像,成本最低、見效最快。
  2. 組合多個元件:例如標題欄——左邊返回鍵、中間標題、右邊操作按鈕,用布局拼起來再封裝一次即可。
  3. 完全重寫 onDraw:自由度最高,圖表、進度條、自訂動畫之類的效果基本都靠這條路。

三種流派沒有高下之分,只有合不合適。多數時候,能從第一種解決的問題,就不必動用第三種。

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