Android 设置二级列表的adapter 父列表有一个 子数据多个 demo、
时间: 2024-03-11 11:48:46 浏览: 88
好的,以下是一个简单的二级列表的demo,父列表有一个子数据多个的情况。
首先是XML布局文件,包含一个ExpandableListView控件:
```xml
<ExpandableListView
android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
接下来是ExpandableListAdapter的实现,包含两个数据集:parentList和childList。parentList包含父列表项的数据,childList是一个Map,包含每个父列表项下的所有子列表项。在本例中,每个父列表项只有一个子列表项。
```java
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private String[] parentList = {"Parent 1", "Parent 2", "Parent 3"};
private Map<String, String[]> childList = new HashMap<>();
public MyExpandableListAdapter() {
childList.put("Parent 1", new String[]{"Child 1"});
childList.put("Parent 2", new String[]{"Child 1", "Child 2", "Child 3"});
childList.put("Parent 3", new String[]{"Child 1", "Child 2"});
}
@Override
public int getGroupCount() {
return parentList.length;
}
@Override
public int getChildrenCount(int groupPosition) {
String parent = parentList[groupPosition];
return childList.get(parent).length;
}
@Override
public Object getGroup(int groupPosition) {
return parentList[groupPosition];
}
@Override
public Object getChild(int groupPosition, int childPosition) {
String parent = parentList[groupPosition];
return childList.get(parent)[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) {
String parentText = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(parentText);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(childText);
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
```
在Activity中,获取ExpandableListView控件并设置ExpandableListAdapter:
```java
ExpandableListView expandableListView = findViewById(R.id.expandableListView);
expandableListView.setAdapter(new MyExpandableListAdapter());
```
通过以上代码,您可以创建一个简单的二级列表,父列表项只有一个子列表项。如果您需要在父列表项下显示多个子列表项,只需要在childList中添加多个子列表项即可。
阅读全文