Jim
Jim

Reputation: 1005

Get number of selected items in android ListView

I have a multiselection ListView in my android app. What I need to know is how many items on that list I have selected.

Upvotes: 2

Views: 7729

Answers (3)

Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42642

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++;
    }
} 

Upvotes: 2

Jim
Jim

Reputation: 1005

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++;
        }
    }
}

Upvotes: 3

RaphMclee
RaphMclee

Reputation: 1623

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

Upvotes: 6

Related Questions