Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 視圖控件架構解析:View 與 ViewGroup

編輯:Android 開發實例

控件樹的組成

Android 的視圖控件大致分為兩類:ViewGroup 與 View。ViewGroup 充當父容器,負責包含並管理子 View,兩者交錯組合便形成一棵控件樹,每個 ViewGroup 與 View 都是樹上的節點。查找控件時依樹的深度遍歷;上層控件負責下層的測量、繪製與事件傳遞。

Android 控件樹:

Android UI 界面架構圖:

一、測量工具:MeasureSpec

  1. 它同時封裝了測量模式與測量大小,分別用 MeasureSpec.getMode() 與 MeasureSpec.getSize() 取得。
  2. 它是一個 32 位元的 int:高 2 位存模式,低 30 位存尺寸。用位運算打包的目的是提升效率。

二、三種測量模式

  • EXACTLY(精確值):layout_width / layout_height 指定為明確數值或 match_parent。
  • AT_MOST(最大值):指定為 wrap_content。
  • UNSPECIFIED:View 想多大就多大。

三、View 預設只支援 EXACTLY

View 類別預設的 onMeasure() 只處理 EXACTLY 模式。要支援其他模式就必須自行覆寫,模板如下:

package com.example.demoapp.views;

import android.content.Context;
import android.view.View;

public class MeasuredView extends View {
    public MeasuredView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 交給父類處理,它最終會呼叫 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

取得 Canvas 的兩種途徑

  1. 由方法參數傳入,例如 onDraw(Canvas canvas) 中的 canvas。
  2. 自行建構:Canvas canvas = new Canvas(bitmap)。傳入 Bitmap 的過程稱為「畫布的裝載」,該 Bitmap 承載所有繪製在 Canvas 上的像素;後續呼叫 drawBitmap() 等方法,實際作用對象就是這張 Bitmap。

繪圖要點

  1. 透過 Canvas.drawXXX() 的繪製會直接改寫 Bitmap,下次刷新 View 時看到的就是被改寫後的內容。
  2. 搭配 Canvas 與 Paint 一起使用。
  3. 再複雜精美的畫面都能拆解成一格格圖形單元,找出這些單元就能把控件畫出來。

五、ViewGroup 的測量

  1. 職責是管理子 View,包括大小與位置。
  2. 遍歷子 View 並呼叫各自的 measure,收集測量結果。
  3. 測量完成後呼叫子 View 的 layout(),把它們放到正確位置。
  4. 自訂 ViewGroup 時通常要覆寫 onLayout() 來控制排列。
  5. 若要支援 wrap_content,必須覆寫 onMeasure()。

六、ViewGroup 的繪製

一般情況下 ViewGroup 自己不需要繪製,它會透過 dispatchDraw() 負責畫出子 View。

七、自訂 View 的要点

  1. 通常要覆寫 onDraw() 決定顯示內容;若要支援 wrap_content,還得覆寫 onMeasure()。
  2. 透過自訂 attrs 屬性可以擴充新的 View 屬性。

幾個重要的回呼時機:

  • onFinishInflate():從 XML 載入完成後回呼。
  • onSizeChanged():尺寸變動時回呼。
  • onMeasure():進行測量。
  • onLayout():決定顯示位置。
  • onTouchEvent():處理觸控事件。

常見的三種實作路線:

  1. 覆寫 onDraw() 擴充原生控件。
  2. 用組合的方式,繼承一個合適的 ViewGroup,再以 addView() 塞入各具功能的子控件,組成複合控件。
  3. 直接繼承 View 打造全新控件:覆寫 onDraw() 與 onMeasure() 處理繪製,覆寫 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 讀取:

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();
    }
}

另外可定義回呼介面,讓自訂控件對外提供靈活的控制方式。

在布局中引用:先宣告命名空間 xmlns:custom="https://schemas.android.com/apk/res-auto",之後就能用 custom: 前綴使用自訂屬性。

<?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():處理觸控互動。

掌握控件樹的結構與這三個階段的職責,自訂控件的行為就完全在自己的掌控之中。

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