我正在使用AlertDialog和多項選擇來顯示可檢查項目列表。如何記住多選擇提示對話框中的選定值?
當用戶選擇一些值時,我可以得到他們的索引並保存到列表中。這工作正常。
但我希望當用戶再次打開AlertDialog有他選擇之前選定/檢查值。
下面是代碼:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMultiChoiceItems(R.array.array_cousine, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
seletedItems.add(++indexSelected);
} else if (seletedItems.contains(indexSelected)) {
seletedItems.remove(Integer.valueOf(++indexSelected));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String[] expList = getResources().getStringArray(R.array.array_cousine);
for (int i = 0; i < seletedItems.size(); i++) {
int selected = seletedItems.get(i);
String selectedString = expList[selected - 1];
selectedItemsName.add(selectedString);
}
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < selectedItemsName.size(); j++) {
String text = selectedItemsName.get(j);
stringBuilder = stringBuilder.append(" "+text);
}
Log.d("TAG", "String builder: " + stringBuilder);
tvCusine.setText(stringBuilder);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
Dialog dialog = builder.create();//AlertDialog dialog;
dialog.show();
這裏是圖片:
是的,我知道第二個參數接受布爾值,我傳遞null,因爲我不知道如何動態地將值添加到布爾[]。 – Zookey
您不能動態更改大小。您可以通過調用boolean [position] = value來隨時更改值。你也可以有一個布爾列表的佈列表,然後在創建實例化警報對話框時調用arraylist.toArray - 馬庫斯胡珀13秒前編輯 –
我已經嘗試了第二種解決方案,它不起作用。我現在會嘗試第一個解決方案。 – Zookey