在 Fragment 中為 ListView 添加頭部視圖(包含 ViewPager),調用 inflater.inflate(R.layout.otherfragment, container, false) 後 addHeaderView,運行崩潰:
ClassCastException: ViewPager$LayoutParams cannot be cast to AbsListView$LayoutParams
LayoutInflater.inflate(layout, parent, false) 中的 parent 用於生成正確的 LayoutParams(匹配父容器類型)。container 是 ViewGroup(Fragment 容器),生成的 LayoutParams 為 ViewGroup.LayoutParams 或其子類。ListView.addHeaderView 要求子視圖持有 AbsListView.LayoutParams,類型不匹配導致崩潰。// 錯誤
View view2 = inflater.inflate(R.layout.otherfragment, container, false);
// 正確:傳入 null,不依附任何父容器生成 LayoutParams
View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.otherfragment, null);
// 或
View headerView = inflater.inflate(R.layout.otherfragment, null); // 同理
list.addHeaderView(headerView);
ListView/GridView/RecyclerView 的頭部/尾部/項目視圖,inflate 時 parent 必須傳 null,由 AdapterView 內部在添加時自動生成匹配的 LayoutParams。
layout_height 或在 onMeasure 中測量),否則可能顯示異常。RecyclerView + HeaderAdapter 替代 ListView,架構更現代、擴展性更強。