自定義ViewGroup中通過FragmentTransaction.replace()添加Fragment,Fragment的onCreateView正常執行且返回非空View,但界面卻不顯示Fragment內容。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 缺失 measureChildren() 或手動 measureChild()
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 正常layout子View
for(int i=0; i<2; i++) {
View child = getChildAt(i);
// ... 佈局邏輯
}
}
自定義ViewGroup必須在onMeasure中顯式測量子View。Fragment的View作為子View添加時,若不調用measureChild()或measureChildren(),子View測量寬高為0,導致onLayout時實際佈局區域為0,內容自然不可見。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 關鍵:測量所有子View
measureChildren(widthMeasureSpec, heightMeasureSpec);
// 或針對性測量
// measureChild(fragmentView, widthMeasureSpec, heightMeasureSpec);
}
onMeasure:確定自身尺寸 → 測量子View尺寸onLayout:根據測量結果 → 定位子View位置onDraw:繪製內容measureChildren()measureChild()一行measureChildren()解決大問題,自定義ViewGroup開發必記心間。