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

Android LayoutInflater.from(getContext()) 炸裂:根因是布局根標籤用了 ,應改為 等 ViewGroup

     編輯:程式設計疑難解答

自定義 ArrayAdapter 中 getView() 調用 LayoutInflater.from(getContext()).inflate(resourceId, null) 導致閃退,Logcat 卡在 inflate 行。經典原因:**布局文件根標籤是 <fragment>,而 inflate() 期望 View/ViewGroup 根節點**。

錯誤代碼片段

// FruitAdapter.java
View view = LayoutInflater.from(getContext()).inflate(resourceId, null); // 閃退點
ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);

問題布局 (fruit_item.xml)

<!-- 錯誤:根標籤是 fragment -->
<fragment xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

修正布局

<!-- 正確:根標籤是 ViewGroup (LinearLayout/RelativeLayout/FrameLayout 等) -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_gravity="center_vertical"
        android:textSize="18sp" />

</LinearLayout>

為什麼 會炸?

  • LayoutInflater.inflate() 解析 XML 並創建 View 層級。
  • <fragment> 是特殊標籤,需經過 FragmentManager 實例化 Fragment、執行生命週期、附加到容器,**不能靜態 inflate 為普通 View**。
  • 嘗試 inflate 會拋出 InflateException: Binary XML file line #1: Error inflating class fragment。

避坑清單

  1. 列表項布局**永遠用 ViewGroup 根標籤**(LinearLayout/RelativeLayout/ConstraintLayout/FrameLayout)。
  2. inflate(resourceId, null) 第二參 null 表示不附加到父容器,ListView/RecyclerView 會自動添加,這沒問題。
  3. 若需在列表項嵌入 Fragment,請用 RecyclerView + FragmentStateAdapter (ViewPager2) 或 FragmentContainerView (API 29+),而非 ListView/GridView。
  4. 調試技巧:Log.d("TAG", "before inflate") / after inflate 定位崩潰行,配合 try-catch 打印異常堆疊。

現代最佳實踐

  • 棄用 ArrayAdapter + ListView,改用 RecyclerView + ViewHolder + DiffUtil,性能更強、API 更清晰。
  • 布局用 ConstraintLayout 減少嵌套,配合 ViewBinding/DataBinding 替代 findViewById。

記住:inflate() 只認 View/ViewGroup 根節點, 走 FragmentManager。換個根標籤,閃退即刻消失。

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