Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the equivilent of getCheckedItemCount() for API level < 11?

I am using this method to check how many items on a list a checked and I get this error that this method is not available for any SDK older than 11.

What is the equivalent this in API level 8

like image 817
code511788465541441 Avatar asked Sep 08 '12 12:09

code511788465541441


3 Answers

The accepted answer didn't work for me (always returns 0), I had to use the following code:

public static int getCheckedItemCount(ListView listView)
{
    if (Build.VERSION.SDK_INT >= 11) return listView.getCheckedItemCount();
    else
    {
        int count = 0;
        for (int i = listView.getCount() - 1; i >= 0; i--)
            if (listView.isItemChecked(i)) count++;
        return count;
    }
}
like image 67
Takhion Avatar answered Sep 30 '22 21:09

Takhion


getCheckedItemIds().length seems to do the trick

like image 33
vharron Avatar answered Sep 30 '22 21:09

vharron


I'm using this code which I believe is efficient and works in all cases:

public int getCheckedItemCount() {
    ListView listView = getListView();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return listView.getCheckedItemCount();
    }

    SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
    int count = 0;
    for (int i = 0, size = checkedItems.size(); i < size; ++i) {
        if (checkedItems.valueAt(i)) {
            count++;
        }
    }
    return count;
}

Please inform me if you find a case where it doesn't work.

like image 36
BladeCoder Avatar answered Sep 30 '22 20:09

BladeCoder