在Android中,要对Spinner的选项进行分组,你可以使用ArrayAdapter
结合自定义布局来实现。以下是一个简单的示例,展示了如何对Spinner的选项进行分组:
spinner_item_group.xml
),用于显示每个分组项。这个布局可以包含一个TextView来显示分组名称,以及其他子项的布局。<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:id="@+id/group_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:textColor="@color/black" />
</LinearLayout>
spinner_item.xml
),用于显示每个分组内的子项。<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinner_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:padding="8dp" />
List<Map<String, Object>> groupedData = new ArrayList<>();
Map<String, Object> group1 = new HashMap<>();
group1.put("title", "Group 1");
group1.put("items", Arrays.asList("Item 1.1", "Item 1.2", "Item 1.3"));
groupedData.add(group1);
Map<String, Object> group2 = new HashMap<>();
group2.put("title", "Group 2");
group2.put("items", Arrays.asList("Item 2.1", "Item 2.2"));
groupedData.add(group2);
// 更多分组...
ArrayAdapter
来绑定分组数据和子项布局。public class GroupedArrayAdapter extends ArrayAdapter<Map<String, Object>> {
public GroupedArrayAdapter(@NonNull Context context, int resource, @NonNull List<Map<String, Object>> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.spinner_item_group, parent, false);
TextView groupTitle = convertView.findViewById(R.id.group_title);
groupTitle.setText((String) getItem(position).get("title"));
} else {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.spinner_item, parent, false);
TextView spinnerItem = convertView.findViewById(R.id.spinner_item);
spinnerItem.setText((String) getItem(position - 1).get("items").get(0));
}
return convertView;
}
@Override
public int getCount() {
return getItemCount() + 1;
}
}
GroupedArrayAdapter
将分组数据绑定到Spinner。Spinner spinner = findViewById(R.id.spinner);
GroupedArrayAdapter adapter = new GroupedArrayAdapter(this, R.layout.spinner_item_group, groupedData);
spinner.setAdapter(adapter);
现在,你的Spinner应该能够显示分组选项和每个分组内的子项。注意,这个示例仅用于演示目的,你可能需要根据你的需求进行调整。