在Android中,要在ExpandableListView中嵌套子列表,您需要创建一个自定义的适配器,该适配器继承自BaseAdapter
- 首先,创建一个自定义的ExpandableListAdapter类,继承自BaseAdapter。
public class CustomExpandableListAdapter extends BaseAdapter { private Context context; private ListgroupHeaders; private List > childItems; public CustomExpandableListAdapter(Context context, List
groupHeaders, List > childItems) { this.context = context; this.groupHeaders = groupHeaders; this.childItems = childItems; } // Other overridden methods like getCount(), getItem(), getGroupId()... }
- 在自定义适配器类中实现
getGroupView()
和getChildView()
方法。这些方法用于创建和显示子项和组头。
@Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // Inflate the layout for group headers LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_group, null, true); TextView groupTextView = (TextView) convertView.findViewById(R.id.group_text); groupTextView.setText(groupHeaders.get(groupPosition)); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // Inflate the layout for child items LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_item, null, true); TextView childTextView = (TextView) convertView.findViewById(R.id.child_text); childTextView.setText(childItems.get(groupPosition).get(childPosition)); return convertView; }
- 在布局文件中创建ExpandableListView。
- 在Activity或Fragment中设置适配器。
ExpandableListView expandableListView = findViewById(R.id.expandableListView); ListgroupHeaders = new ArrayList<>(); // Add your group headers here List > childItems = new ArrayList<>(); // Add your child items here. Each child item should be a List containing the text for each child view. CustomExpandableListAdapter adapter = new CustomExpandableListAdapter(this, groupHeaders, childItems); expandableListView.setAdapter(adapter);
现在,您应该可以在ExpandableListView中看到嵌套的子列表了。根据需要自定义布局和适配器以适应您的应用程序需求。