您应该只调用一次,但在初始化后保存对加载程序的引用。解决此问题的一种方法是保留从View
到的地图YouTubeThumbnailLoader
。中getView
,有 3 种情况:
- 视图是新的,需要初始化。
- 视图已经初始化,我们有一个对加载器的引用。
- 视图当前正在初始化。
在情况 1 和 3 中,您需要记住加载程序在初始化时应该执行的操作。例如,您可以将视频 ID 保存在视图的标签中。
示例代码:
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;
}
在你的 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);
}