1. 程式人生 > 實用技巧 >自定義ViewGroup步驟,child.measure()方法,measureChild()方法,setmeasuredDimension()方法

自定義ViewGroup步驟,child.measure()方法,measureChild()方法,setmeasuredDimension()方法

若在文中涉及到不清楚的知識點請看前面的文章

自定義ViewGroup首先就要繼承於ViewGroup:

構造方法也是必須要實現的,

自定義ViewGroup必須要實現的方法還有兩個,onMeasure,onLayout方法

在onMeasure方法對自控制元件進行測量,以確定父控制元件的大小,同時也可以在該方法中指定子控制元件的大小

在onMeasure方法中確定了父控制元件的大小,也知道了子控制元件的大小,在onLayout方法中就只是對子控制元件進行佈局

1:child.measure(引數1,引數2)方法

通過該方法來告知父檢視子檢視的大小與模式,

引數1:由子檢視的寬與模式組成

引數2:由子檢視的高與模式組成

得到該引數的方式有兩種

(1):通過MeasureSpec.makeMeasureSpec(引數1.1,引數1.2)方法

引數1.1是子檢視的大小,這個大小要麼是寬度,要麼是高度,引數1.2是子檢視的模式,模式又分為3種

MeasureSpec.EXACTLY:表示精確的,比如我告訴你寬20,那就是20,和父容器一樣寬,大小很明確

MeasureSpec.AT_MOST:表示最大值,最大不能超過多少

MeasureSpec.UNSPECIFIED:無限制

val child = getChildAt(0)  //得到子檢視
val childWidth = parentWidth - 2*space //獲取子檢視的寬度

val childHeight = parentHeight -2*space //獲取子檢視的高度
val chidWidthSpec = MeasureSpec.makeMeasureSpec(childWidth,MeasureSpec.EXACTLY)
val childHeightSpec = MeasureSpec.makeMeasureSpec(childHeight,MeasureSpec.EXACTLY)
child.measure(chidWidthSpec,childHeightSpec)
(2):通過getChildMeasureSpec(引數2.1,引數2.2,引數2.3)方法·,

引數2.1:父容器寬度或高度的Spec,
引數2.2:子檢視與父容器兩邊間隙之和,
引數2.3:子檢視本身的大小
val child = getChildAt(0)
//獲取控制元件的佈局引數
val lp = child.layoutParams //獲取子檢視的佈局引數
val childWidthSpec = getChildMeasureSpec(widthMeasureSpec,32,lp.width) //widthMeasureSpec父檢視的寬度的spec,
32是子檢視與父檢視兩邊的間距之和,lp.width是子檢視的寬度
val childHeightSpec = getChildMeasureSpec(heightMeasureSpec,32,lp.height)
child.measure(childWidthSpec,childHeightSpec)
(3):通過
measureChild(child,widthMeasureSpec,heightMeasureSpec),
child:第一個引數,對哪個子檢視進行測量,
後面兩個分別是父檢視的寬度和高度的spec,
2:設定父容器的大小
setMeasureDimension(w,h),
w:是父檢視的寬度
h:是父檢視的高度
3:對子檢視的佈局
child.Layout(左邊,上邊,右邊,下邊)