2

I have a listview where each list item can contain 1 or more clickable images. Clicking them starts an activity that shows a full screen version of the image.

The following code (slightly simplified) sets up the OnClickListeners within my GetView() implementation, for each image in each ListItem. This worked perfectly.

ImageView imageView = (ImageView)convertView.findViewById(R.id.image_res);
imageView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        ActivityLauncher.startPhotoViewerActivity(mContext, item);
    }
});

However, to improve performance, I decided to store each view in memory after constructing it the first time. I do this instead of using convertView because there are 4-5 different types of Views and they are sometimes dynamically constructed in code hence making re-use difficult.

As soon as I start storing the views in memory and then returning the already constructed views during subsequent calls to getView() based on the position, the performance significantly improves but the OnClickListeners start behaving funky.

Specifically, now when a given image is tapped, the OnClickListener for it may fire immediately or not at all. In the cases where it does not fire immediately, it may fire as soon as one starts scrolling. If this doesn't trigger the OnClickListener to run, clicking back (to quit the activity) may trigger it. If this doesn't trigger it, then closing all activities by pressing BACK) and then re-entering the app will trigger all the queued OnClickListeners. In one case I clicked 25 times on various images with no result. Then I closed all the activities and then clicked the application icon once again which opened all 25 image previews.

Any idea as to what is causing this? What is interesting to me is that the OnClickListeners are obviously set correctly because they do open the photo viewer activity at some point in time. The wrong image is never opened and there is never a case where they NEVER fire. The problem is that they may fire immediately or much later.

Is it not recommended to save the Views for each list item and return them based on position from within getView() like I am doing? Any help is greatly appreciated.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Goat
  • 193
  • 10
  • 1
    You should post your whole `getView()` method, otherwise it will be very hard to diagnose why this specific behavior is happening. – dmon Oct 30 '11 at 14:12

1 Answers1

3

Watch the talk on ListViews given at Google I/O. At 13:45, they specifically warn against caching views and returning them. If one does this, it can lead to strange behavior, which is exactly what I am experiencing. Given this, the question is moot.

http://www.youtube.com/watch?v=wDBM6wVEO70

Hope this helps someone in the future avoid the same pitfalls. Caching views is NOT RECOMMENDED!!!

Goat
  • 193
  • 10