Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTubeThumbnailView in ListView

Google has released the YouTube api for Google. In that api is a YouTubeThumbnailView to display thumbnails of a movie. I want to display the thumbnails in a ListView. I have made a adapter to make the views. But I'm not sure how to handle this.

In the getView of my ListView-adapter I inflate a layout which include the YouTubeThumbnailView. According to the documentation (https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeThumbnailView) I should call the initialize method.

I'm wondering if I need to call the initialize method one time or also call this if the view is re-used by the ListView? There is no way to check if the YouTubeThumbnailView is already initialized? So I guess I should call it multiple times. But I have no idea if that is allowed?

like image 433
Peter Fortuin Avatar asked Dec 26 '12 22:12

Peter Fortuin


1 Answers

You should only call it once, but save a reference to the loader once it's initialized. One way to deal with this is to keep a map from View to YouTubeThumbnailLoader. In getView, there are 3 cases:

  1. The view is new and needs to be initialized.
  2. The view is already initialized and we have a reference to the loader.
  3. The view is currently initializing.

In case 1 and 3, you need to remember what the loader should do when it's initialized. You can e.g. save the video id in the tag of the view.

Example code:

Map<View, YouTubeThumbnailLoader> loaders;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  View view = convertView;
  String videoId = getVideoId(position);

  if (view == null) {
    // Case 1 - We need to initialize the loader
    view = inflater.inflate(..., parent, false);
    YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
    thumbnail.setTag(videoId);
    thumbnail.initialize(DeveloperKey.DEVELOPER_KEY, thumbnailListener);
  } else {
    YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
    YouTubeThumbnailLoader loader = loaders.get(thumbnail);
    if (loader == null) {
      // Case 3 - The loader is currently initializing
      thumbnail.setTag(videoId);
    } else {
      // Case 2 - The loader is already initialized
      thumbnail.setImageResource(R.drawable.loading_thumbnail);
      loader.setVideo(videoId);
    }
  }
  return view;
}

And in your thumbnailListener:

  @Override
  public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
    String videoId = (String) view.getTag();
    loaders.put(view, loader);
    view.setImageResource(R.drawable.loading_thumbnail);
    loader.setVideo(videoId);
  }
like image 191
Anton Hansson Avatar answered Oct 28 '22 04:10

Anton Hansson