要解决Android可扩展列表视图中组项无法展开/折叠的问题,可以根据以下步骤进行操作:
public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
private List groupItems;
private Map> childItems;
public ExpandableListViewAdapter(Context context, List groupItems, Map> childItems) {
this.context = context;
this.groupItems = groupItems;
this.childItems = childItems;
}
@Override
public int getGroupCount() {
return groupItems.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return childItems.get(groupItems.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
return groupItems.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return childItems.get(groupItems.get(groupPosition)).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.group_item_layout, parent, false);
}
TextView groupItemTextView = convertView.findViewById(R.id.groupItemTextView);
groupItemTextView.setText((String) getGroup(groupPosition));
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.child_item_layout, parent, false);
}
TextView childItemTextView = convertView.findViewById(R.id.childItemTextView);
childItemTextView.setText((String) getChild(groupPosition, childPosition));
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private ExpandableListViewAdapter expandableListViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandableListView);
// 初始化数据源
List groupItems = new ArrayList<>();
groupItems.add("Group 1");
groupItems.add("Group 2");
Map> childItems = new HashMap<>();
List childItemsGroup1 = new ArrayList<>();
childItemsGroup1.add("Child 1.1");
childItemsGroup1.add("Child 1.2");
List childItemsGroup2 = new ArrayList<>();
childItemsGroup2.add("Child 2.1");
childItemsGroup2.add("Child 2.2");
childItems.put(groupItems.get(0), childItemsGroup1);
childItems.put(groupItems.get(1), childItemsGroup2);
// 设置适配器
expandableListViewAdapter = new ExpandableListViewAdapter(this, groupItems, childItems);
expandableListView.setAdapter(expandableListViewAdapter);
}
}