要實現 Android 選擇框的分組功能,可以使用 ExpandableListView 控件來展示分組列表,并在每個分組下面展示可選擇的子項。
首先,在布局文件中添加 ExpandableListView 控件:
<ExpandableListView
android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
然后,創建一個適配器類來管理分組和子項的數據,并綁定到 ExpandableListView 控件上:
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> groups;
private Map<String, List<String>> items;
public MyExpandableListAdapter(Context context, List<String> groups, Map<String, List<String>> items) {
this.context = context;
this.groups = groups;
this.items = items;
}
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return items.get(groups.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return items.get(groups.get(groupPosition)).get(childPosition);
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// Implement how to display group view
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// Implement how to display child view
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
@Override
public boolean hasStableIds() {
return false;
}
// Other required methods
}
在 getGroupView 和 getChildView 方法中實現如何展示分組和子項的視圖。
最后,在 Activity 或 Fragment 中設置 ExpandableListView 控件和適配器:
ExpandableListView expandableListView = findViewById(R.id.expandableListView);
List<String> groups = new ArrayList<>();
groups.add("Group 1");
groups.add("Group 2");
Map<String, List<String>> items = new HashMap<>();
List<String> group1Items = new ArrayList<>();
group1Items.add("Item 1");
group1Items.add("Item 2");
items.put("Group 1", group1Items);
List<String> group2Items = new ArrayList<>();
group2Items.add("Item A");
group2Items.add("Item B");
items.put("Group 2", group2Items);
MyExpandableListAdapter adapter = new MyExpandableListAdapter(this, groups, items);
expandableListView.setAdapter(adapter);
這樣就可以實現一個具有分組功能的選擇框。