java - listView setItemChecked 不工作

标签 java android listview android-alertdialog

我有一个多选对话框,在单击按钮时弹出。 下图显示了它的外观。

enter image description here

问题来了。当我点击 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/

相关文章:

java - 如何从 10/21/2009 转换为 Wed Oct 21 18 :48:12 UTC+0530 2009

Android:如何从 Atom 获取链接

java - Android 进度对话框未关闭

WPF ListView在内部布局面板周围有一个像素边框。我如何摆脱它?

JavaFx ListView 不显示文本,但在 cellFactory 之后工作

Java - 平衡 ThreadPoolExecutor 公平地为并行请求提供线程

java - 带有Opera和Edge浏览器的远程Webdriver

java - JViewport.BACKINGSTORE_SCROLL_MODE 和 setOpaque(false)

android - 适用于 Android 或 iOS 的视频聊天 SDK 可用吗?

listview - Flutter: Animation - 如何制作动画列表?