我有一个多选对话框,在单击按钮时弹出。 下图显示了它的外观。
问题来了。当我点击 select all
时,我使用 listView.setItemChecked(position, true)
以编程方式检查所有项目。那部分有效。但在那之后,当用户取消选中列表中的特定项目时,我想取消选中 全选
。
下面是我的代码,我不知道为什么它不起作用。
private CharSequence[] itemList = {"select all", "one", "two", "three", "four", "five", "six"};
private boolean[] itemBooleanList = new boolean[]{false, false, false, false, false, false, false};
final AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
myDialog.setTitle("Select type(s)");
myDialog.setMultiChoiceItems(itemList, itemBooleanList, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
final ListView listView = ((AlertDialog)dialog).getListView();
if(indexSelected == 0){ // if "select all" is clicked - check/uncheck all items
for(int i=0; i<itemList.length; i++){
listView.setItemChecked(i, isChecked);
itemBooleanList[i] = isChecked;
}
}else{
itemBooleanList[indexSelected] = isChecked;
}
// now I check if all item in boolean[] are true or false, if one of the item is false, it returns false and `select all` can be unchecked
final boolean areAllTrue = areBooleanAllTrue(itemBooleanList);
listView.setItemChecked(0, areAllTrue);
System.out.println(Arrays.toString(itemBooleanList));
}
}).show();
PS:当我打印 itemBooleanList
时,如果用户取消选中某个项目,我确实看到该索引处的 boolean 值设置为 false,这意味着逻辑是正确的,它只是 setItemChecked
没有完成它的工作。
如果您希望我上传更多代码或屏幕截图,请告诉我。
最佳答案
我希望下面的代码能解决问题,
final ListView listView = ((AlertDialog)dialog).getListView();
if(indexSelected == 0){ // if "select all" is clicked - check/uncheck all items
for(int i=0; i<itemList.length; i++){
listView.setItemChecked(i, isChecked);
itemBooleanList[i] = isChecked;
}
}else{
itemBooleanList[indexSelected] = isChecked;
if(!isChecked) {
itemBooleanList[0] = false;
listView.setItemChecked(0, false);
}else{
//check whether all the items are checked otherthan 'select all'
//if true then
//itemBooleanList[0] = true;
//listView.setItemChecked(0, true);
}
}
关于java - listView setItemChecked 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42638839/