在Android中,要在ExpandableListView中嵌套子列表,您需要?jiǎng)?chuàng)建一個(gè)自定義的適配器,該適配器繼承自BaseAdapter
public class CustomExpandableListAdapter extends BaseAdapter {
private Context context;
private List<String> groupHeaders;
private List<List<String>> childItems;
public CustomExpandableListAdapter(Context context, List<String> groupHeaders, List<List<String>> childItems) {
this.context = context;
this.groupHeaders = groupHeaders;
this.childItems = childItems;
}
// Other overridden methods like getCount(), getItem(), getGroupId()...
}
getGroupView()
和getChildView()
方法。這些方法用于創(chuàng)建和顯示子項(xiàng)和組頭。@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
android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
ExpandableListView expandableListView = findViewById(R.id.expandableListView);
List<String> groupHeaders = new ArrayList<>();
// Add your group headers here
List<List<String>> 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);
現(xiàn)在,您應(yīng)該可以在ExpandableListView中看到嵌套的子列表了。根據(jù)需要自定義布局和適配器以適應(yīng)您的應(yīng)用程序需求。