要实现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数组来获取所选项的状态。