Android ViewGroup使用小結

來源:互聯網
上載者:User

標籤:android

ViewGroup定義

在api中是這麼描述ViewGroup的:A ViewGroup is a special view that can contain other views. 根據意思我們可以明白,在ViewGroup中可以包含其他UI控制項,包括我們的自訂控制項

優勢及用處

我們瞭解UI控制項最大的目的是使用它。而要瞭解控制項,必須明白該控制項的優點。ViewGroup在Android的UI控制項中相對複雜,它的自訂程度很高,藉助declare-styleable自訂控制項屬性,幾乎控制項的各個方便都可以控制到。

瞭解到這些優點之後,你會想到哪裡有ViewGroup的用武之地呢?考慮考慮,我會在文章最後說說我的理解。

繪製流程

ViewGroup中有兩個及其重要的回調方法

  • onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  • onLayout(boolean changed, int left, int top, int right, int bottom)
onMeasure

Ask all children to measure themselves and compute the measurement of this layout based on the children.

onLayout

Position all children within this layout.

以上是api中對兩個方法的解釋,真實使用中onMeasure和onLayout都可能被調用多次,根據log我們會發現onLayout都是在onMeasure之後才調用,這也證實了api的說法,ViewGroup在繪圖之前先把數值算好,然後根據對應的值把控制項繪製到相對應的地方。

getMeasuredWidth

這個方法在這裡單獨拿出來說一下,在onMeasure方法中計算控制項存放位置時,我們會用到getMeasuredWidth()和getMeasuredHeight(),這裡得到的值包括padding,不包括margin,在計算的時候要注意

Android ViewGroup使用小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.