android 向上展开和收起 示例
时间: 2023-12-11 12:04:33 浏览: 35
以下是一个基本的展开和收起示例,使用 ExpandableListView 组件实现:
1. 在您的布局文件中添加一个 ExpandableListView 组件:
```xml
<ExpandableListView
android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
```
2. 创建一个适配器类来管理数据和视图。在这个示例中,我们将使用 SimpleExpandableListAdapter 类,它是 BaseExpandableListAdapter 的一个简单实现。创建适配器的代码如下:
```java
String[] groups = {"Group 1", "Group 2", "Group 3"};
String[][] children = {{"Child 1", "Child 2", "Child 3"}, {"Child 4", "Child 5", "Child 6"}, {"Child 7", "Child 8", "Child 9"}};
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < groups.length; i++) {
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put("GROUP_NAME", groups[i]);
List<Map<String, String>> childrenList = new ArrayList<Map<String, String>>();
for (int j = 0; j < children[i].length; j++) {
Map<String, String> curChildMap = new HashMap<String, String>();
childrenList.add(curChildMap);
curChildMap.put("CHILD_NAME", children[i][j]);
}
childData.add(childrenList);
}
SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] {"GROUP_NAME"},
new int[] {android.R.id.text1},
childData,
android.R.layout.simple_expandable_list_item_2,
new String[] {"CHILD_NAME"},
new int[] {android.R.id.text1}
);
```
3. 将适配器设置为 ExpandableListView 的适配器:
```java
ExpandableListView expandableListView = findViewById(R.id.expandableListView);
expandableListView.setAdapter(adapter);
```
4. 设置 ExpandableListView 的 OnGroupClickListener 和 OnChildClickListener,以处理用户单击组或子项时的操作:
```java
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if (parent.isGroupExpanded(groupPosition)) {
parent.collapseGroup(groupPosition);
} else {
parent.expandGroup(groupPosition);
}
return true;
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
// 处理子项点击事件
return true;
}
});
```
在这个示例中,我们使用 SimpleExpandableListAdapter 类来创建适配器,并在 OnGroupClickListener 中实现展开和收起组的逻辑。当用户单击组时,我们检查它是否已经展开,如果是,则将其收起;如果没有,则将其展开。