我在Stackoverflow上找到了如何使用复选框创建警告对话框。它工作得很好。我的问题是,我如何检查哪些复选框被选中?我使用复选框来设置正在保存的文本文件的文件名。
final CharSequence[] items = {" Custom/Default Filename ", "With Date&Time "," With this device's model "};
// arraylist to keep the selected items
final ArrayList seletedItems=new ArrayList();
AlertDialog dialog2 = new AlertDialog.Builder(Settings.this)
.setTitle("Select, what export file's name contains")
.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
// write your code when user checked the checkbox
seletedItems.add(indexSelected);
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove it
// write your code when user Uchecked the checkbox
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// What I should to in this step, to detect which checkboxes are checked and which are not? That's my problem.
// Your code when user clicked on OK
// You can write the code to save the selected item here
}
}).create();
dialog2.show();
答案 0 :(得分:1)
不使用通用列表,而是使用布尔值列表并在ischecked
中存储
final List<Boolean> seletedItems = Arrays.asList(false,false,false)
// or final List<Boolean> seletedItems = new ArrayList<>();
// for(int i =0;i<items.length;i++){seletedItems.add(false);}
并将数据存储为相应的索引
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
seletedItems.set(indexSelected,isChecked);
// add boolean check at the particular position
}
注意:列表的大小等于根据位置保持选择的数组大小
假设,用户选择0,2,然后seletedItems
将
index value
0 true
1 false
2 true
您也可以使用boolean
数组来提高效率