views:

47

answers:

1

I've implemented a GridView based on this tutorial. It works great unless open up the search dialog or rotate the screen then scroll around.

When the search dialog and virtual keyboard appear, the drawables for each of my grid items shift. I can click on them and they do what I expect, except the drawable is wrong.

The same problem happens when I go into landscape mode and scroll around. If I scroll down, up, the down again, the drawables are shuffled.

For better illustration, let's say I have three objects, each with an image.

  • Obj A shows an Apple
  • Obj B shows a Banana
  • Obj C shows a Cantaloupe

When the shift occurs I end up with:

  • Obj A shows an Cantaloupe
  • Obj B shows a Banana
  • Obj C shows a Apple

The problem isn't consistent between the two causes (search dialog and screen rotate n' scroll), but each cause itself is consistent. Scrolling around repeatedly reveals a pattern as does the search dialog appearing. How can I stop this from happening?

+1  A: 

The source code you link to is flawed.

You cannot just set the text and image when the layout is inflated in getView(), as that code demonstrates. You need to set the text and image every time, whether it is for a newly-inflated layout or one that you are recycling via convertView.

The key is in the term "recycling". If convertView is not null, that means it is some existing View that you inflated earlier that Android wants you to repopulate with new data based on the supplied position. The code you link to ignores that part.

Here is an excerpt from one of my books that covers the concept of recycling in adapters. While the excerpt focuses on ListView, the technique is identical for GridView.

CommonsWare
Thanks! The "Getting Fancy With Lists" chapter cleared up a lot of questions I've had. My GridView is working beautifully now.
originalbryan