自定義 MyLayout extends FrameLayout 內含 ImageView、TextView,在 Activity.addView(myLayout) 正常顯示;但放入自定義 MyGroup extends ViewGroup 的構造器 addView(myLayout) 後,僅顯示 FrameLayout 背景,子 View 消失。
ViewGroup **不自動測量/佈局子 View**;FrameLayout 等具體佈局類重寫了 onMeasure/onLayout。直接繼承 ViewGroup 必須自己實現:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec); // 測量所有子 View
setMeasuredDimension(resolveSize(maxChildWidth, widthMeasureSpec),
resolveSize(maxChildHeight, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.layout(l, t, l + child.getMeasuredWidth(), t + child.getMeasuredHeight());
}
}
}
ViewGroup 源碼與 FlowLayout 開源實現。|