如何使用Youtube API在RecyclerView中加载Youtube缩略图

26

我正在尝试在RecyclerView中加载Youtube视频缩略图,但我遇到了一些问题。

这是我在适配器中所做的:

public static class ItemViewHolder extends RecyclerView.ViewHolder {

    private YouTubeThumbnailView thumb;
    public  Post                 post;

    public ItemViewHolder(View v) {
        thumb = (YouTubeThumbnailView) v.findViewById(R.id.youtube_thumbnail);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof ItemViewHolder) {

            ((ItemViewHolder) holder).thumb.initialize(YOUTUPEKEY, new YouTubeThumbnailView.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
                    youTubeThumbnailLoader.setVideo(VIDEOID);

                }

                @Override
                public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {

                }});
}}}

它能正常工作,但我不确定自己是否做得正确。当我在另一个活动中使用相同的适配器时,会出现这个错误:

Activity com.example.yasser.version6.Mespublications has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@4252bcb8 that was originally bound here

有时候在滑动时,加载缩略图需要时间,并且有时它们之间会混淆。

我添加了一个释放所有 YouTube 加载器的函数:

public void ReleaseLoaders() {
    for (YouTubeThumbnailLoader loader : loaders.values()) {
        loader.release();
    }
}

我正在从Activity Onstop()中调用此函数:

@Override
public void onStop() {
    super.onStop();
    mAdapter.ReleaseLoaders();
}

它运行得很好一段时间,但有时会崩溃。


你有没有看过这个SO的帖子?它似乎有你遇到的相同问题 - 内存泄漏,而不是RecyclerView,看起来你已经处理了那个。 - adjuremods
错误来自于Recyclerview适配器。 - Stranger B.
你如何初始化你的适配器? - random
4个回答

32

你可以尝试这个方法,它不使用API但是很快。

使用Picasso从以下URL中加载图像到recycler view:

https://img.youtube.com/vi/“在此处输入您的视频ID”/{{default.jpg}}

-- 编辑 --

经过一些研究和实验:

要获取默认的全尺寸缩略图,请改用0.jpg而不是default.jpg

https://img.youtube.com/vi/"在此处输入您的视频ID"/{{0.jpg}}

这里是链接:http://www.reelseo.com/youtube-thumbnail-image/

编辑2:

刚刚发现有人在SO上已经给出了类似我的答案,并提供了更多解释和选项供您选择。

如何从YouTube API获取YouTube视频缩略图?


最终编辑:

这是可行的代码。我最近使用了该API制作了一个应用程序,所以我发现为什么您会收到错误。这是因为您没有正确释放加载器。

您可以通过两种方式释放加载器/加载器。

第一种

(首选,在接下来的几秒钟内您将看到原因) 您需要在图像加载到视图中并且有一个监听器OnThumbNailLoadedListener时释放它。这就是我释放它的地方(如果您注意下面的代码)。这意味着您不必再处理此实例。一旦缩略图加载完成,您就完成了。

第二种

由于getView()被频繁调用,您必须释放新的YouTubeThumbnailLoader实例。这意味着您必须将所有这些存储在ArrayList中。只需进行高级for循环并在activity停止时调用所有内容中的release即可。

现在你可能已经明白为什么第一种方式更受欢迎了。我知道你选择了第二个选项,只是想让你知道第一个选项始终可以保证正常工作(至少在我的情况下是这样的)。我在一个 Activity 中使用了一个 YouTubeSupportFragment,它运行得很好,没有任何问题。你肯定可以让第二个选项工作,但我认为你需要处理很多特殊情况。
final YouTubeThumbnailView youTubeThumbnailView = (YouTubeThumbnailView) convertView.findViewById(R.id.show_episode_thumbnail);
    youTubeThumbnailView.initialize(DeveloperKey.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
            youTubeThumbnailLoader.setVideo(videoId);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
                @Override
                public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                    youTubeThumbnailLoader.release();
                }

                @Override
                public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {

                }
            });
        }

        @Override
        public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {

        }
    });

我刚刚对我的回答做了一个很好的修改。我建议你去看一下。 - Arnold Balliu
非常感谢啊,伙计..!! - Saurabh Singh

15

onBindViewHolder 中,您正在尝试一遍又一遍地初始化相同的 YoutubeThumbnailView ,而不是在 onCreateViewHolder 中创建视图时只初始化一次。通过将视频 ID 设置为标签添加到 YoutubeThumbnailView 中,您可以防止缩略图混乱或加载错误。


适配器。

    private class ThumbnailAdapter extends RecyclerView.Adapter{

    private final int UNINITIALIZED = 1;
    private final int INITIALIZING = 2;
    private final int INITIALIZED = 3;
    private int blackColor = Color.parseColor("#FF000000");
    private int transparentColor = Color.parseColor("#00000000");

    public class VideoViewHolder extends RecyclerView.ViewHolder{

        public YouTubeThumbnailView ytThubnailView = null;
        public ImageView ivYtLogo = null;
        public TextView tvTitle = null;

        public VideoViewHolder(View itemView) {
            super(itemView);
            ytThubnailView = (YouTubeThumbnailView) itemView.findViewById(R.id.yt_thumbnail);
            ivYtLogo = (ImageView) itemView.findViewById(R.id.iv_yt_logo);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);

            initialize();
        }

        public void initialize(){
            ivYtLogo.setBackgroundColor(blackColor);
            ytThubnailView.setTag(R.id.initialize, INITIALIZING);
            ytThubnailView.setTag(R.id.thumbnailloader, null);
            ytThubnailView.setTag(R.id.videoid, "");

            ytThubnailView.initialize(API_KEY, new YouTubeThumbnailView.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
                    ytThubnailView.setTag(R.id.initialize, INITIALIZED);
                    ytThubnailView.setTag(R.id.thumbnailloader, youTubeThumbnailLoader);

                    youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
                        @Override
                        public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String loadedVideoId) {
                            String currentVideoId = (String) ytThubnailView.getTag(R.id.videoid);
                            if(currentVideoId.equals(loadedVideoId)) {
                                ivYtLogo.setBackgroundColor(transparentColor);
                            }
                            else{
                                ivYtLogo.setBackgroundColor(blackColor);
                            }
                        }

                        @Override
                        public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
                            ivYtLogo.setBackgroundColor(blackColor);
                        }
                    });

                    String videoId = (String) ytThubnailView.getTag(R.id.videoid);
                    if(videoId != null && !videoId.isEmpty()){
                        youTubeThumbnailLoader.setVideo(videoId);
                    }
                }

                @Override
                public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
                    ytThubnailView.setTag(R.id.initialize, UNINITIALIZED);
                    ivYtLogo.setBackgroundColor(blackColor);
                }
            });
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = getLayoutInflater().inflate(R.layout.row_video_item, parent, false);
        VideoViewHolder videoViewHolder = new VideoViewHolder(view);
        return videoViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final Entities e = entities.get(position);
        final VideoViewHolder videoViewHolder = (VideoViewHolder) holder;
        videoViewHolder.tvTitle.setText(e.name);
        videoViewHolder.ivYtLogo.setVisibility(View.VISIBLE);
        videoViewHolder.ytThubnailView.setTag(R.id.videoid, e.id);
        videoViewHolder.ivYtLogo.setBackgroundColor(blackColor);

        int state = (int) videoViewHolder.ytThubnailView.getTag(R.id.initialize);

        if(state == UNINITIALIZED){
            videoViewHolder.initialize();
        }
        else if(state == INITIALIZED){
            YouTubeThumbnailLoader loader = (YouTubeThumbnailLoader) videoViewHolder.ytThubnailView.getTag(R.id.thumbnailloader);
            loader.setVideo(e.id);
        }
    }

    @Override
    public int getItemCount() {
        return entities.size();
    }
}

每一行所使用的布局为:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <com.google.android.youtube.player.YouTubeThumbnailView
        android:id="@+id/yt_thumbnail"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/iv_yt_logo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="center"
        android:src="@mipmap/youtube_play"
        android:background="#00000000"
        android:layout_centerInParent="true"/>

</RelativeLayout>

<TextView
    android:id="@+id/tv_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="#FF000000"
    android:textSize="16sp"
    android:text="Title"/>

<View
    android:id="@+id/seperator"
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    android:background="#FF642108"/>

</LinearLayout>

tags.xml.

位置: src/main/res/values/tags.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="initialize" />
<item type="id" name="videoid"/>
<item type="id" name="thumbnailloader"/>
</resources>

输入图片描述


谢谢您的回复,但我已经尝试过了,缩略图仍然混合! - Stranger B.
我在我的应用程序中使用它。它运行良好。缩略图不会混乱。 - Harish_N

2
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoHolder> {

    private List<VideoPojo> listvideo;
    private VideoPojo videoPojo;
    private Context mContext;
    private boolean readyForLoadingYoutubeThumbnail = true;
    String KEY = "AIzaSyA5kyaLgS7MKxS19uHf2CUsIOmDkv92DGU";

    public VideoAdapter(Context context, List<VideoPojo> listvideo) {
        this.listvideo = listvideo;
        this.mContext = context;
        videoPojo = new VideoPojo();
    }

    @Override
    public VideoAdapter.VideoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_layout, parent, false);
        return new VideoHolder(view);
    }

    @Override
    public void onBindViewHolder(final VideoAdapter.VideoHolder holder, final int position) {

        holder.murl.setText(listvideo.get(position).getVideoUrl());
        final String url = listvideo.get(position).getVideoUrl();
        Log.d(TAG, "readyForLoadingYoutubeThumbnail" + readyForLoadingYoutubeThumbnail);
        if (readyForLoadingYoutubeThumbnail) {
            Log.d(TAG, "initializing for youtube thumbnail view...");
            readyForLoadingYoutubeThumbnail = false;
            holder.youTubeThumbnailView.initialize(KEY, new YouTubeThumbnailView.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(final YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {

                    youTubeThumbnailLoader.setVideo(url);
                    youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {

                        @Override
                        public void onThumbnailLoaded(YouTubeThumbnailView childYouTubeThumbnailView, String s) {
                            holder.loding.setVisibility(View.GONE);
                            youTubeThumbnailLoader.release(); // spy ga memory lick
                        }

                        @Override
                        public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
                            youTubeThumbnailLoader.release(); // spy ga memory lick
                        }
                    });

                    readyForLoadingYoutubeThumbnail = true;
                }

                @Override
                public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
                    //do nohing.. ada error, tambahin method ini jalan, error-nya lupa...
                    readyForLoadingYoutubeThumbnail = true;
                }
            });
        }
        holder.mdelate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteVideoAlertDialog(listvideo.get(holder.getAdapterPosition()).getId(), holder.getAdapterPosition());
            }
        });

    }

    @Override
    public int getItemCount() {
        // Log.v(VideoAdapter.class.getSimpleName(), "" + listvideo.size());
        return listvideo.size();
    }

    public class VideoHolder extends RecyclerView.ViewHolder {

        YouTubeThumbnailView youTubeThumbnailView;
        protected FrameLayout playButton;
        TextView murl, mdelate;
        ImageView loding;

        public VideoHolder(View itemView) {
            super(itemView);
            mdelate = itemView.findViewById(R.id.mdelate);
            murl = itemView.findViewById(R.id.murl);
            playButton = itemView.findViewById(R.id.btnYoutube_player);
            youTubeThumbnailView = itemView.findViewById(R.id.youtube_thumbnail);
            loding = itemView.findViewById(R.id.loding);

            playButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    String url = listvideo.get(position).getVideoUrl();
                    Toast.makeText(mContext, url, Toast.LENGTH_SHORT).show();
                    Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) mContext,
                            KEY, url, 100, false, true);
                    mContext.startActivity(intent);
                }
            });
        }

    }

    private void deleteVideoAlertDialog(final int row_id, final int adapterPosition) {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("Delete");
        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want to delete this video");
        alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (SQLiteHelper.deleteUser(mContext, row_id)) {
                    listvideo.remove(adapterPosition);
                    notifyItemRemoved(adapterPosition);
                    notifyItemRangeChanged(adapterPosition, listvideo.size());
                } else {
                    Toast.makeText(mContext, "internal issue ", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();

    }

    public boolean addNewVideo(String Url, Context context) {
        videoPojo.setVideoUrl(Url);
        SQLiteHelper sqLiteHelper = new SQLiteHelper(context);
        if (sqLiteHelper.addNewVideo(context, videoPojo)) {
            listvideo.add(videoPojo);
            notifyDataSetChanged();
            Toast.makeText(context, "video Saved", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
}

0

从此URL获取高质量图像:

https://img.youtube.com/vi/<VIDEO_ID_HERE>/maxresdefault.jpg

然后使用Picasso或Glide库加载它。

对于这个视频 "https://www.youtube.com/watch?v=BEScHJrjsmU", VIDEO_ID 是 "BEScHJrjsmU"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接