public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = findViewById(R.id.group); // ❌ 錯誤:調用的是 Activity.findViewById
// ...
}
findViewById 是 **Activity/View** 的方法。在 Adapter 中直接調用等同於 this.findViewById (即 Activity.findViewById),只會在 **Activity 的佈局樹** 中查找,而 R.id.group 定義在**單獨的 Item 佈局 XML** 中,自然找不到 → 返回 null → 後續操作空指針。
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
// 1. 將 Item 佈局膨脹為 View 對象
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.group_item, parent, false);
}
// 2. 在膨脹後的 View 上查找控件
TextView title = view.findViewById(R.id.biaoti);
ImageView icon = view.findViewById(R.id.tubiao);
// 3. 綁定數據
title.setText(getGroup(groupPosition).toString());
return view;
}
LayoutInflater.inflate():將 XML 佈局轉為 View 對象樹。view.findViewById():在**該 View 子樹**中查找,而非整個 Activity。convertView 復用機制:非 null 時直接復用,避免重複 inflate 提升效能。static class GroupViewHolder {
TextView title;
ImageView icon;
}
public View getGroupView(...) {
View view = convertView;
GroupViewHolder holder;
if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.group_item, parent, false);
holder = new GroupViewHolder();
holder.title = view.findViewById(R.id.biaoti);
holder.icon = view.findViewById(R.id.tubiao);
view.setTag(holder);
} else {
holder = (GroupViewHolder) view.getTag();
}
holder.title.setText(getGroup(groupPosition).toString());
return view;
}