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

Android View 與 ViewGroup 架構解析:測量、排版與繪製

編輯:關於 Android 程式設計

Android 的視圖控制項大致分為兩類:ViewGroup 與 View。ViewGroup 作為父容器,包含並管理子 View;兩者共同構成一棵「控制項樹」,每個 ViewGroup 與 View 就是樹上的節點。查找控制項時以樹的深度遍歷,而上層控制項負責下層子控制項的測量、配置與事件傳遞。

Android 控制項樹:

Android UI 介面架構:

一、測量工具類:MeasureSpec

  • MeasureSpec 封裝了「測量模式」與「測量大小」,分別用 MeasureSpec.getMode() 與 MeasureSpec.getSize() 取得。
  • 它是一個 32 位元的 int:高 2 位為模式,低 30 位為大小。用位運算打包的目的是為了在頻繁傳遞的測量流程中降低物件配置帶來的效能損耗。

二、三種測量模式

  • EXACTLY(精確值模式):對應 layout_width/layout_height 指定具體數值或 match_parent。此時上層已經明確告訴你該有多大,直接採用即可。
  • AT_MOST(最大值模式):對應 wrap_content。上層給了一個上限,你要在這個範圍內決定自己的大小。
  • UNSPECIFIED:不受限制,View 想多大就多大,通常出現在 ScrollView 這類容器對子 View 的測量中。

三、View 預設的 onMeasure() 只支援 EXACTLY

要支援其他模式就必須自行覆寫 onMeasure(),模板如下:

 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) {
         // 呼叫父類的 onMeasure()
         super.onMeasure(measureWidth(widthMeasureSpec),
                         measureHeight(heightMeasureSpec));
         // 或者直接呼叫 setMeasuredDimension(),因為父類 onMeasure() 最終也是呼叫它
         // setMeasuredDimension(measureWidth(widthMeasureSpec),
         //                      measureHeight(heightMeasureSpec));
     }

     /** 測量 View 的寬度 */
     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;
     }

     /** 測量 View 的高度 */
     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;
     }
 }

這段程式示範了一個關鍵觀念:處理 AT_MOST 時,一定要用 Math.min() 把自己的期望值與上層給的上限取小,否則自訂 View 會撐破父容器。

四、View 的繪製

1. Canvas 的取得方式

  • 由方法參數傳入,例如 View.onDraw(Canvas canvas) 的參數就是一個 Canvas。
  • 透過建構子建立:Canvas canvas = new Canvas(bitmap)。傳入 Bitmap 的過程稱為「畫布的裝載」,該 Bitmap 承載了所有繪製在 Canvas 上的像素;此後呼叫 canvas.drawBitmap() 等方法,實際作用的對象就是這個 Bitmap。

2. 繪製的幾個要點

  • Canvas 的 drawXXX 系列方法會直接作用於所關聯的 Bitmap,因此下次刷新 View 時,看起來就像 Bitmap 的內容改變了。
  • 搭配 Paint 可以控制顏色、樣式、線寬等繪製屬性。
  • 再複雜精美的控制項,都能拆解成一個個小的圖形單元。找出這些單元,就能把它畫出來。

五、ViewGroup 的測量

  • ViewGroup 的職責是管理子 View,包括子 View 的大小與位置。
  • 它遍歷所有子 View,逐一呼叫子 View 的 measure() 取得各自的測量結果。
  • 測量完成後,再呼叫子 View 的 layout() 把它們放到正確位置。
  • 自訂 ViewGroup 時,通常要覆寫 onLayout() 來控制子 View 的擺放。
  • 若要支援 wrap_content,必須覆寫 onMeasure()。

六、ViewGroup 的繪製

一般情況下 ViewGroup 本身不需要繪製內容,但它會透過 dispatchDraw() 來繪製它的子 View。

七、自訂 View 的要点

  • 通常要覆寫 onDraw() 繪製顯示內容;若需支援 wrap_content,還必須覆寫 onMeasure()。
  • 透過自訂 attrs 屬性,可以為新 View 加上專屬屬性。

View 的重要回呼時機

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

自訂 View 的三種常見路徑

  • 覆寫 onDraw(),對原生控制項做擴充。
  • 用「組合」做出新控制項:繼承一個合適的 ViewGroup,再用 addView() 加入具備特定功能的小控制項,組合成複合控制項。
  • 直接繼承 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 取值(取完務必 recycle):

 package com.jy.myrecyclerview.test;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.util.AttributeSet;
 import android.view.View;
 import com.jy.myrecyclerview.R;

 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":

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

把整條鏈串起來看:MeasureSpec 由父容器傳下來 → onMeasure 決定自己的尺寸 → onLayout 決定子 View 的位置 → onDraw/dispatchDraw 完成繪製。自訂控制項時遇到的多數問題,都能回到這條流程上定位是哪一步出了錯。

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