简体   繁体   中英

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. 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 :

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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