自定義 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);
<!-- 錯誤:根標籤是 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**。InflateException: Binary XML file line #1: Error inflating class fragment。LinearLayout/RelativeLayout/ConstraintLayout/FrameLayout)。inflate(resourceId, null) 第二參 null 表示不附加到父容器,ListView/RecyclerView 會自動添加,這沒問題。RecyclerView + FragmentStateAdapter (ViewPager2) 或 FragmentContainerView (API 29+),而非 ListView/GridView。Log.d("TAG", "before inflate") / after inflate 定位崩潰行,配合 try-catch 打印異常堆疊。ArrayAdapter + ListView,改用 RecyclerView + ViewHolder + DiffUtil,性能更強、API 更清晰。ConstraintLayout 減少嵌套,配合 ViewBinding/DataBinding 替代 findViewById。記住:inflate() 只認 View/ViewGroup 根節點,