getView called with wrong position when scrolling fast
You are correct that ListView
is reusing views in different places on the screen. It's an optimization to keep memory use reasonable and speedy by not allocating new views all the time.
Chances are that you're using LiewView
incorrectly. Watch this talk on how to properly use ListView
to get the whole story, but here's the highlights:
- "Position" refers to the location of your data in the adapter list. If your adapter data is in an array, this would be the index into that array.
- "ID" refers to the value of the data itself. If you have a list of names and resort them, their position will change, but their ID will not.
- "Index" refers to the relative location of a view with respect to the viewable screen area. You'll probably never need this.
- Do not manipulate views (or attempt to cache them) outside of your adapter's
getView()
method or you will get strange behavior. - If the call to
getView(int, View, ViewGroup)
provides a view instance, populate its fields instead of inflating totally new views. Assuming you've correctly implementedgetItemType()
, you'll always get the rightView
type to repopulate. - Make your
getView()
method as fast as you possibly can, and only do heavy lifting on other threads. - Just because the container called
getView()
doesn't necessarily mean the data will be displayed. The framework uses these for measurement purposes. Since the work could be thrown away, this is another reason to make sure thatgetView()
is as fast as you can make it. - When something happens to your data which you need to show on screen, say your download is complete, that's when you call
notifyDataSetChanged()
. Don't fiddle with the views directly, they'll be populated on the next UI loop when it gets redrawn.
Having just spent a few days reworking a ListView
that was implemented naively, I feel your pain. The results have been worth it, though!
i had the same problem: into the adapter i was changing background color in the getView method but sometimes the listview was "reciclyng" views (getting the wrong background). I solved simply putting "else" to each
if(...){changeBackground}
I added
else {restore default background}
And then it worked smoothly
always use this approach in getview: convertView = inflater.inflate(R.layout.listinflate, parent, false);
And let your activity implements onScrollListener and when the user is flinging notify your listview adapter to never mind taking efforts to update the items correctly. and when the user is no more flinging tell the adapter to take care about providing data in getView.
That solved my all problems. And one more thing do not use wrap_content in the list view height. set smoothscroll false in it too.