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

Android自定義ViewGroup嵌入Fragment視圖不顯示:onMeasure缺失measureChild

     編輯:程式設計綜合問答

問題現象

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

完整流程對照

  1. onMeasure:確定自身尺寸 → 測量子View尺寸
  2. onLayout:根據測量結果 → 定位子View位置
  3. onDraw:繪製內容

避坑指南

  • 繼承ViewGroup時必須重寫onMeasure和onLayout
  • 容器類ViewGroup調用measureChildren()
  • 單一子View用measureChild()
  • Fragment的View屬於普通View,同樣遵循測量-佈局流程

一行measureChildren()解決大問題,自定義ViewGroup開發必記心間。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved