以下是我的AlertDialog.Builder
final String[] values = new String[] {"Select All", "Android", "ios", "windows", "Blackberry"};
final ArrayList<String> selecteditems = new ArrayList<String>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select your favorite OS");
builder.setMultiChoiceItems(values, null , new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selecteditems.add(String.valueOf(which));
} else {
selecteditems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
我想要做的是能够检测何时选中'全选',我可以从isChecked
循环中检测到。但是我希望能够在用户选中“全选”时设置要检查的所有选项,并在用户取消选中“全选”时删除检查。
答案 0 :(得分:3)
它应该类似于以下代码。关键点是提供boolean[]
checkedItems
数组,并在您尝试选择全部时更新它。
checkedItems
数组(因为Dialog仍然引用它。)应为每个项目调用dialog.getListView().setItemChecked(i, true);
。
items.add(0, "Select All");
boolean[] checkedItems = new boolean[items.size()];
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(dialogTitle)
.setMultiChoiceItems(items.toArray(new String[items.size()]), checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if(which == 0) {
if(isChecked) {
multichoiceDialog.getListView().setItemChecked(0, true);
checkedItems[0] = true;
for(int i=1; i< checkedItems.length; i++) {
checkedItems[i] = true;
multichoiceDialog.getListView().setItemChecked(i, true);
}
}
}
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
multichoiceDialog = builder.create();
multichoiceDialog.show();