简体   繁体   English

带有复选框的Android自定义列表视图检测是否未选中任何复选框

[英]Android custom listview with checkbox detect if no checkbox is checked

I have a menu item wherein if it is clicked I need to check first if a checkbox is checked. 我有一个菜单项,如果单击该菜单项,则需要首先检查是否已选中一个复选框。 If not then display a toast message. 如果没有,则显示祝酒消息。

This is what I've tried so far: 到目前为止,这是我尝试过的:

On menu item click: 在菜单项上单击:

 SparseBooleanArray checkedPositions = lv.getCheckedItemPositions();
            int size = checkedPositions.size();
            for (int i = 0 ; i < size ; i++) {
                // We get the key stored at the index 'i'
                int key = checkedPositions.keyAt(i);
                // We get the boolean value with the key
                Log.i ("SavedItems", "checkedPositions(" + key + ") = " + checkedPositions.get(key));
            }

            if(size < 1) {
                Toast.makeText(getActivity(), "No item selected", Toast.LENGTH_SHORT).show();
            } 

This is working if no checkbox is checked but if I check and uncheck it's not firing the toast message. 如果未选中任何复选框,但如果我选中并取消选中它未触发Toast消息,则此方法有效。 Any ideas? 有任何想法吗? Thanks. 谢谢。

To show Message accoding to if any item is checked or not in ListView use SparseBooleanArray.indexOfValue which will return index of checked item otherwise return -1 : 要在ListView中显示是否已对任何项目进行检查的消息SparseBooleanArray.indexOfValue ,请使用SparseBooleanArray.indexOfValue ,它将返回被检查项目的索引,否则返回-1

SparseBooleanArray checkedPositions = lv.getCheckedItemPositions();
int isItemChecked=checkedPositions.indexOfValue(true);

if(isItemChecked>0){
     Toast.makeText(getActivity(), "ItemChecked : " +isItemChecked +
         " Value :"+checkedPositions.get(isItemChecked), Toast.LENGTH_SHORT).show();
}else{
       Toast.makeText(getActivity(), "No item selected", Toast.LENGTH_SHORT).show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM