在 Android 中,要實現下拉框控件的多選功能,可以使用 Spinner
和 AlertDialog
結合的方式
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<!-- 在這里添加 CheckBox 控件 -->
</LinearLayout>
</ScrollView>
public class MainActivity extends AppCompatActivity {
private Spinner mSpinner;
private List<String> mItems = Arrays.asList("Item 1", "Item 2", "Item 3");
private Set<String> mSelectedItems = new HashSet<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner = findViewById(R.id.spinner);
initSpinner();
}
private void initSpinner() {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
showMultiSelectDialog();
}
return true;
});
}
private void showMultiSelectDialog() {
// 在這里顯示 AlertDialog,并處理多選邏輯
}
}
showMultiSelectDialog()
方法中,顯示 AlertDialog 并處理多選邏輯:private void showMultiSelectDialog() {
LayoutInflater inflater = LayoutInflater.from(this);
View dialogView = inflater.inflate(R.layout.dialog_multiselect, null);
LinearLayout container = dialogView.findViewById(R.id.container);
for (int i = 0; i < mItems.size(); i++) {
final int index = i;
CheckBox checkBox = new CheckBox(this);
checkBox.setText(mItems.get(i));
checkBox.setChecked(mSelectedItems.contains(mItems.get(i)));
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
mSelectedItems.add(mItems.get(index));
} else {
mSelectedItems.remove(mItems.get(index));
}
});
container.addView(checkBox);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
builder.setPositiveButton("確定", (dialog, which) -> {
String selectedText = TextUtils.join(", ", mSelectedItems);
mSpinner.setPrompt(selectedText);
dialog.dismiss();
});
builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
builder.show();
}
現在,當用戶點擊 Spinner 時,將顯示一個包含多個 CheckBox 的 AlertDialog。用戶可以在其中進行多選操作,然后點擊“確定”按鈕關閉對話框。所選項目將顯示在 Spinner 中。