在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應該能夠顯示分組選項和每個分組內的子項。注意,這個示例僅用于演示目的,你可能需要根據你的需求進行調整。