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

Android 視圖控件架構剖析:View、ViewGroup、測量與自訂控件

編輯:關於 Android 開發

Android 視圖控件架構剖析:View、ViewGroup、測量與自訂控件

Android 的視圖控件大致分成兩類:ViewGroup 與 View。ViewGroup 是父容器,負責包含並管理子 View;兩者層層嵌套之後就形成一棵控件樹,每個 ViewGroup 與 View 都是樹上的節點。查找控件時沿著樹的深度遍歷,上層控件則負責下層的測量、配置與事件轉發。

Android 控件樹:

Android UI 界面架構圖:

一、測量用的工具類:MeasureSpec

MeasureSpec 同時裝了「測量模式」與「測量大小」兩份資訊,分別用 getMode() 與 getSize() 取出。它其實只是一個 32 位元的 int:高 2 位存模式,低 30 位存尺寸。用位元運算打包,主要是為了效能。

三種測量模式

  • EXACTLY(精確值):layout_width/layout_height 寫成具體數值或 match_parent。
  • AT_MOST(最大值):寫成 wrap_content,大小不得超過父容器給的上限。
  • UNSPECIFIED:不設限,View 想多大就多大。

View 預設的 onMeasure() 只支援 EXACTLY。想支援其他模式就必須自己覆寫,模板如下:

public class MeasuredView extends View {

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 呼叫父類的 onMeasure();它最終也會走到 setMeasuredDimension()
        super.onMeasure(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
        // 或者直接:setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
    }

    /** 測量寬度 */
    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = 200;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    /** 測量高度 */
    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = 200;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }
}

二、View 的繪製

取得 Canvas 的兩種方式:一是由方法參數傳入,例如 onDraw(Canvas canvas);二是自己 new,把一張 Bitmap 交給它,這個過程稱為「畫布的裝載」,之後所有 drawXXX 的像素都會落在那張 Bitmap 上。

實作時通常會搭配 Paint 指定顏色、樣式與抗鋸齒。再怎麼複雜精美的介面,拆開來也不過是一堆基本圖形單元的組合——找出這些單元,控件就畫得出來。

三、ViewGroup 的測量與配置

  • ViewGroup 的職責是管理子 View 的大小與位置。
  • 它遍歷每個子 View,呼叫對方的 measure() 取得測量結果。
  • 量完之後呼叫子 View 的 layout(),把它放到正確座標。
  • 自訂 ViewGroup 時通常要覆寫 onLayout() 來決定子 View 的呈現位置。
  • 若要支援 wrap_content,onMeasure() 一定要覆寫。
  • ViewGroup 本身多半不需要繪製內容,它會用 dispatchDraw() 把繪製工作分派給子 View。

四、自訂 View 的三種常見做法

  1. 覆寫 onDraw(),在原生控件的基礎上擴充。
  2. 用組合的方式:繼承一個合適的 ViewGroup,再用 addView() 塞進各具功能的子控件,組出複合控件。
  3. 直接繼承 View 寫全新控件,覆寫 onDraw()/onMeasure() 處理繪製,覆寫 onTouchEvent() 處理互動。

幾個值得記住的回呼時機:onFinishInflate()(XML 載入完成)、onSizeChanged()(尺寸變動)、onMeasure()(測量)、onLayout()(定位)、onTouchEvent()(觸摸事件)。此外,定義回呼介面能讓自訂控件的對外控制更靈活。

五、自訂屬性

在 res/values 下新增 attrs.xml 宣告屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="customAttr">
        <attr name="title" format="string" />
        <attr name="fontSize" format="dimension" />
        <attr name="fontColor" format="color" />
        <attr name="background" format="reference|color" />
        <attr name="fontStyle" format="enum" />
        <attr name="shadeSupport" format="boolean" />
    </declare-styleable>
</resources>

在程式中用 TypedArray 把屬性集讀出來,取值時記得給預設值,用完一定要 recycle():

public class TestCustomAttrs extends View {

    private Context mContext;
    private AttributeSet mAttrs;
    private String mTitle;
    private float mFontSize;
    private int mFontColor;
    private int mBackground;
    private int mFontStyle;
    private boolean mShadeSupport;

    public TestCustomAttrs(Context context) {
        super(context);
        this.mContext = context;
    }

    public TestCustomAttrs(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        this.mAttrs = attrs;
    }

    public TestCustomAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        this.mAttrs = attrs;
    }

    private void getCustomAttrs() {
        TypedArray ta = mContext.obtainStyledAttributes(mAttrs, R.styleable.customAttr);
        mTitle        = ta.getString(R.styleable.customAttr_title);
        mFontSize     = ta.getDimension(R.styleable.customAttr_fontSize, 10);
        mFontColor    = ta.getColor(R.styleable.customAttr_fontColor, 0);
        mBackground   = ta.getColor(R.styleable.customAttr_background, 0);
        mFontStyle    = ta.getInt(R.styleable.customAttr_fontStyle, 0);
        mShadeSupport = ta.getBoolean(R.styleable.customAttr_shadeSupport, false);
        ta.recycle();
    }
}

六、在 XML 中引用自訂控件

自訂控件要先宣告命名空間 xmlns:custom="https://schemas.android.com/apk/res-auto",之後就能用 custom:xxx 的方式指定屬性:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.jy.myrecyclerview.test.TestCustomAttrs
        android:id="@+id/id_recyclerview"
        android:divider="#ffff0000"
        android:dividerHeight="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        custom:title="title"
        custom:fontSize="12sp"
        custom:fontColor="@color/colorPrimary"
        custom:background="@color/colorPrimary"
        custom:shadeSupport="false" />
</RelativeLayout>

七、自訂 ViewGroup 要覆寫的三個方法

  • onMeasure():測量子 View。
  • onLayout():決定子 View 的位置。
  • onTouchEvent():處理觸摸互動。

本文部分觀念參考徐宜生《Android 群英傳》一書。

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