要实现一个可展开的列表视图适配器,你需要使用ExpandableListView
和BaseExpandableListAdapter
ExpandableListView
。例如,在activity_main.xml
中添加以下代码: android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
MyExpandableListAdapter
,并继承BaseExpandableListAdapter
。在这个类中,你需要实现以下方法:getGroupCount()
: 返回分组的数量。getChildrenCount(int groupPosition)
: 返回指定分组中子项的数量。getGroup(int groupPosition)
: 返回指定分组的数据。getChild(int groupPosition, int childPosition)
: 返回指定子项的数据。getGroupId(int groupPosition)
: 返回分组的ID。getChildId(int groupPosition, int childPosition)
: 返回子项的ID。hasStableIds()
: 返回是否使用稳定的ID。getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
: 返回分组的视图。getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
: 返回子项的视图。isChildSelectable(int groupPosition, int childPosition)
: 返回子项是否可选。MyExpandableListAdapter
类中,实现上述方法。例如:public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// ... 其他代码
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return groups.get(groupPosition).getChildren().size();
}
@Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return groups.get(groupPosition).getChildren().get(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) {
// 实现分组视图
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// 实现子项视图
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity
中设置适配器:public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private MyExpandableListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandableListView);
adapter = new MyExpandableListAdapter();
expandableListView.setAdapter(adapter);
}
}
MyExpandableListAdapter
类中的getGroupView()
和getChildView()
方法中实现。