Why is ListView.getCheckedItemPositions() not returning correct values?

前端 未结 15 1971
北海茫月
北海茫月 2020-11-29 06:01

The app has a ListView with multiple-selection enabled, in the UI it works as expected. But when I read the values out using this code:

Log.         


        
15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 06:39

    This is an old thread but since this basically came up first in current Google search here's a quick way to understand what listView.getCheckedItemPositions() does:

    Unless the list Item wasn't 'toggled' at all in your ListView, it wont be added to the SparseBooleanArray that is returned by listView.getCheckedItemPositions()

    But then, you really don't want your users to click every list item to "properly" add it to the returned SparseBooleanArray right?

    Hence you need to combine the usage of valueAt() AND keyAt() of the SparseBooleanArray for this.

        SparseBooleanArray checkedArray = listView.getCheckedItemPositions();
    
        ArrayList entries = baseAdapter.getBackingArray(); //point this to the array of your custom adapter
    
        if (checkedArray != null)
        {
            for(int i = 0; i < checkedArray.size(); i++)
            {
                if(checkedArray.valueAt(i))    //valueAt() gets the boolean
                    entries.yourMethodAtIndex(checkedArray.keyAt(i)); //keyAt() gets the key
            }
        }
    

提交回复
热议问题