首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 自定義 ViewGroup 子 View 不顯示:onMeasure/onLayout 缺失分析

     編輯:程式設計綜合問答

現象

自定義 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());
        }
    }
}

建議

  • 若只需容器能力,**繼承 FrameLayout/LinearLayout/RelativeLayout** 直接復用佈局邏輯。
  • 確需自定義 ViewGroup,參考 ViewGroup 源碼與 FlowLayout 開源實現。|
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved