標籤: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使用小結