使用 AlertDialog.Builder.setMultiChoiceItems 創建多選對話框,需在用戶點擊「確認」時獲取所有被勾選項目的索引或文本。
// 1. 定義選項與初始狀態
final String[] items = {"Item1", "Item2", "Item3"};
final boolean[] checkedItems = {true, false, false}; // 初始勾選狀態
// 2. 用於記錄最終選擇的數組(長度與 items 一致)
final boolean[] userSelection = new boolean[items.length];
// 3. 構建對話框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("多選對話框")
.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// 實時同步用戶操作到 userSelection
userSelection[which] = isChecked;
}
})
.setPositiveButton("確認", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 4. 遍歷 userSelection 獲取結果
StringBuilder result = new StringBuilder("選中項目:");
for (int i = 0; i < userSelection.length; i++) {
if (userSelection[i]) {
result.append(items[i]).append(" ");
}
}
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
// 此處可進一步處理業務邏輯
}
})
.setNegativeButton("取消", null)
.show();
checkedItems 用於初始化 UI 顯示;userSelection 用於記錄用戶最終交互結果。兩者長度必須一致。which 是被點擊項的索引,isChecked 是點擊後的新狀態。直接賦值給 userSelection[which] 即可。userSelection,配合 items 獲取文本,或直接使用索引。若多處使用,可封裝為通用方法:
public static void showMultiChoiceDialog(Context context, String title, String[] items,
boolean[] initialChecked, OnMultiChoiceResultListener listener) {
final boolean[] selection = new boolean[items.length];
System.arraycopy(initialChecked, 0, selection, 0, items.length);
new AlertDialog.Builder(context)
.setTitle(title)
.setMultiChoiceItems(items, initialChecked, (dialog, which, isChecked) -> selection[which] = isChecked)
.setPositiveButton("確認", (dialog, which) -> listener.onResult(selection, items))
.setNegativeButton("取消", null)
.show();
}
interface OnMultiChoiceResultListener {
void onResult(boolean[] checked, String[] items);
}
關鍵在於維護一個與選項列表等長的布爾數組,在 OnMultiChoiceClickListener 中實時同步狀態,最終在確認回調中讀取。這比在確認時遍歷 Dialog 內部視圖層級獲取 CheckBox 狀態可靠得多。