温馨提示×

如何在ExpandableListView中嵌套

小樊
81
2024-10-14 13:33:01
栏目: 编程语言

在Android中,要在ExpandableListView中嵌套子列表,您需要创建一个自定义的适配器,该适配器继承自BaseAdapter

  1. 首先,创建一个自定义的ExpandableListAdapter类,继承自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()...
}
  1. 在自定义适配器类中实现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;
}
  1. 在布局文件中创建ExpandableListView。
<ExpandableListView
    android:id="@+id/expandableListView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  1. 在Activity或Fragment中设置适配器。
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);

现在,您应该可以在ExpandableListView中看到嵌套的子列表了。根据需要自定义布局和适配器以适应您的应用程序需求。

0