Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating ListView items in Android

I want to iterate a list of items into a ListView. This code below is not enough to iterate all the items into the list because of the weird behaviour of getChildCount() function which only returns the visible item count.

for (int i = 0; i < list.getChildCount(); i++) {
   item = (View)list.getChildAt(i);
   product = (Product)item.getTag();
   // make some visual changes if product.id == someProductId
}

My screen displays 7 results and when there are more than 7 items into the list, it's not possible to access to the 8th item or so.. Only visible items..

Should I use ListIterator instead?

Thanks.

like image 400
pocoa Avatar asked Jan 17 '11 05:01

pocoa


2 Answers

You need to customize your list adapter's getView() method, and put your check inside it to check if the current item's id matches:

Product product = items.get(position);
if(product.id == someProductId) {
    //make visual changes
} else {
    //reset visual changes to default to account for recycled views
}

Since typically only the visible items only exist at a specific time, getView is called whenever more need to be seen. They're created at that time, typically recycling views from the now-invisible items in the list (hence why you want to reset the changes if the criteria does NOT match).

like image 195
Kevin Coppock Avatar answered Sep 16 '22 19:09

Kevin Coppock


So @kcoppock solved your first problem it seems you got another problem. How to update the view item? The android SMS application shows one way:

  1. create your own list view item like this:

    public class MyListItem extends RelativeLayout {
    ...
    }
    

    in your list view item layout file:

    < MyListItem  android:layout_width=.....>
    ...
    </ MyListItem >
    
  2. and in your code, when your view item can be seen, register MyListItem as a data changed listener(the data is up to you). I mean, when your data changed, then you can update the item directly.

Check out the SMS application source code to read more.

like image 33
kevin lynx Avatar answered Sep 18 '22 19:09

kevin lynx