溫馨提示×

如何在ExpandableListView中嵌套

小樊
81
2024-10-14 13:33:01
欄目: 編程語言

在Android中,要在ExpandableListView中嵌套子列表,您需要?jiǎng)?chuàng)建一個(gè)自定義的適配器,該適配器繼承自BaseAdapter

  1. 首先,創(chuàng)建一個(gè)自定義的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. 在自定義適配器類中實(shí)現(xiàn)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;
}
  1. 在布局文件中創(chuàng)建ExpandableListView。
<ExpandableListView
    android:id="@+id/expandableListView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  1. 在Activity或Fragment中設(shè)置適配器。
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)用程序需求。

0