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

Android 自定義 ViewGroup 實作要點總結

編輯:關於 Android 程式設計

自定義 Layout 的兩種類型

一是從零建立新的 ViewGroup,二是繼承既有 Layout 並擴充功能。

核心流程

自定義 View 通常經歷 onMeasure、onLayout、onDraw。ViewGroup 一般重點在測量與擺放子 View,不一定需要實作 onDraw。

LayoutParams 與屬性

若要控制子 View 的比例或邊距,應定義自定義 LayoutParams,並在 generateLayoutParams、generateDefaultLayoutParams 中回傳。XML 屬性透過 declare-styleable 宣告,再在 LayoutParams 建構子中解析。

測量時套用比例

在 measureChildWithMargins 或 onMeasure 中,依 LayoutParams 的比例調整子 View 的 MeasureSpec,即可讓子 View 佔父容器指定比例。

總結:自定義 ViewGroup 要分清自身屬性與子 View 屬性,並善用 support 包中的實作作為參考。

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