要實現Android Spinner的多選功能,可以通過自定義Adapter和布局來實現。以下是一個簡單的實現步驟:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:padding="8dp"/>
<CheckBox
android:id="@+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"/>
</LinearLayout>
public class MultipleChoiceAdapter extends ArrayAdapter<String> {
private boolean[] selectedItems;
public MultipleChoiceAdapter(Context context, List<String> items) {
super(context, 0, items);
selectedItems = new boolean[items.size()];
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_multiple_choice, parent, false);
}
TextView textView = convertView.findViewById(R.id.text_view);
CheckBox checkBox = convertView.findViewById(R.id.check_box);
String item = getItem(position);
if (item != null) {
textView.setText(item);
checkBox.setChecked(selectedItems[position]);
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> selectedItems[position] = isChecked);
}
return convertView;
}
}
Spinner spinner = findViewById(R.id.spinner);
List<String> items = Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4");
MultipleChoiceAdapter adapter = new MultipleChoiceAdapter(this, items);
spinner.setAdapter(adapter);
現在,您可以在Spinner中選擇多個選項,并通過selectedItems數組來獲取所選項的狀態。