getView called with wrong position when scrolling fast

后端 未结 5 1820
臣服心动
臣服心动 2020-12-16 03:17

fairly new Android developer here.

I\'ve come across a strange problem that I\'m not sure how to work around. I\'ve read a lot of problems around here that sound lik

5条回答
  •  -上瘾入骨i
    2020-12-16 03:48

    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:

    1. "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.
    2. "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.
    3. "Index" refers to the relative location of a view with respect to the viewable screen area. You'll probably never need this.
    4. Do not manipulate views (or attempt to cache them) outside of your adapter's getView() method or you will get strange behavior.
    5. 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 implemented getItemType(), you'll always get the right View type to repopulate.
    6. Make your getView() method as fast as you possibly can, and only do heavy lifting on other threads.
    7. 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 that getView() is as fast as you can make it.
    8. 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!

提交回复
热议问题