开发者

Get number of selected items in android ListView

开发者 https://www.devze.com 2023-01-19 20:41 出处:网络
I have a multiselection ListView in my android app. What I ne开发者_如何学Goed to know is how many items on that list I have selected. Use getCheckedItemCount() of ListView. This gives you directly an

I have a multiselection ListView in my android app. What I ne开发者_如何学Goed to know is how many items on that list I have selected.


Use getCheckedItemCount() of ListView. This gives you directly an int.


I found a solution. getCheckedItemPositions() will create a SparceBooleanArray. So it is just to count the elements which are true in that array.

Example:

SparseBooleanArray positions = theListView.getCheckedItemPositions();
int counter = 0;
if (positions != null) {
    int length = positions.size();
    for (int i = 0; i < length; i++) {
        if (positions.get(positions.keyAt(i))) {
            counter++;
        }
    }
}


Instead of using keyAt followed by get, we can use valueAt directly.

SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int count = 0;
for (int i = 0, ei = checkedItemPositions.size(); i < ei; i++) {
    if (checkedItemPositions.valueAt(i)) {
        count++;
    }
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消