Iterating ListView items in Android
Asked Answered
L

3

6

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.

Lashio answered 17/1, 2011 at 5:36 Comment(1)
How are you populating the data , If you are using an adapter, overide the getCount() method of the list adapterAuxochrome
G
1

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).

Gamache answered 17/1, 2011 at 5:50 Comment(3)
Hi kcoppock. Thanks for your reply. Now it works as I expected except it's not updating the visible part of the UI until I scroll. Is there any event that I can trigger to refresh the UI.Lashio
Yup, you can call listView.notifyDatasetChanged();. That will refresh the ListAdapter, however, it should be correct even before scrolling; getView gets called as each view is built. Can you post your ListAdapter's code into the original question?Gamache
Thank you for your help. I'm so sorry to accept it that late. I thought I already accepted. Cheers.Lashio
T
1

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.

Tamer answered 17/1, 2011 at 9:29 Comment(0)
P
0

The number of views in the ListView(7) is different from the number of items in the adapter(which is more than 7) .Try to use a BaseAdapter.

Peanut answered 17/1, 2011 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.