Multiple YouTube video in RecyclerView/ListView in android

Youtube integration in your android application is becoming popular day by day. It is easy to integrate for single video. But it is little difficult for beginner to integrate multiple video inside of RecyclerView. In this tutorial, I will show how to integrate youtube into your app. After all those step below, our output will be like below:

screen_app

Step -01:

To integrate YouTube into your app, you need get your app id from google developer console. In google developer console, you have to enable YouTube data API v3. Now get your app id and save into your app. For me this is my app id:

AIzaSyB9KYC1lOwjVLd-O_I5Zn_XSP0oV2zyTGc

Step -02: Since we have a RecyclerView, you need to create child view for each item. Below is the code for each item view:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:foreground="@drawable/image_ripple"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="0dp"
        android:layout_marginTop="10dp"
        card_view:cardBackgroundColor="@android:color/black"
        android:background="@drawable/border_single_pixel"
        card_view:cardPreventCornerOverlap="false"
        card_view:cardUseCompatPadding="true">


    <com.google.android.youtube.player.YouTubeThumbnailView
        android:id="@+id/youtube_thumbnail"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:scaleType="centerCrop"
        android:visibility="visible"/>

    <RelativeLayout android:id="@+id/relativeLayout_over_youtube_thumbnail"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@color/color_background_transparent"
        android:visibility="visible">

        <ImageView android:id="@+id/btnYoutube_player"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="center"
            android:src="@mipmap/ic_youtube_play_button"/>

    </RelativeLayout>
    </android.support.v7.widget.CardView>

</RelativeLayout>

Step -03: Creating adapter. My code is given below:

package nanofaroque.com.youtubeplayertesting;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
/**
 * Created by ofaroque on 8/13/15.
 */
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.VideoInfoHolder> {

    //these ids are the unique id for each video
    String[] VideoID = {"P3mAtvs5Elc", "nCgQDjiotG0", "P3mAtvs5Elc"};
    Context ctx;

    public RecyclerAdapter(Context context) {
        this.ctx = context;
    }

    @Override
    public VideoInfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        return new VideoInfoHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final VideoInfoHolder holder, final int position) {


        final YouTubeThumbnailLoader.OnThumbnailLoadedListener  onThumbnailLoadedListener = new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){
            @Override
            public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {

            }

            @Override
            public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                youTubeThumbnailView.setVisibility(View.VISIBLE);
                holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
            }
        };

        holder.youTubeThumbnailView.initialize(Resources.KEY, new YouTubeThumbnailView.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {

                youTubeThumbnailLoader.setVideo(VideoID[position]);
                youTubeThumbnailLoader.setOnThumbnailLoadedListener(onThumbnailLoadedListener);
            }

            @Override
            public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
                 //write something for failure
            }
        });
    }

    @Override
    public int getItemCount() {
        return VideoID.length;
    }

    public class VideoInfoHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        protected RelativeLayout relativeLayoutOverYouTubeThumbnailView;
        YouTubeThumbnailView youTubeThumbnailView;
        protected ImageView playButton;

        public VideoInfoHolder(View itemView) {
            super(itemView);
            playButton=(ImageView)itemView.findViewById(R.id.btnYoutube_player);
            playButton.setOnClickListener(this);
            relativeLayoutOverYouTubeThumbnailView = (RelativeLayout) itemView.findViewById(R.id.relativeLayout_over_youtube_thumbnail);
            youTubeThumbnailView = (YouTubeThumbnailView) itemView.findViewById(R.id.youtube_thumbnail);
        }

        @Override
        public void onClick(View v) {

            Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) ctx, Resources.KEY, VideoID[getLayoutPosition()]);
            ctx.startActivity(intent);
        }
    }
}

One of the most important things to know for using youtube is YouTubeThumbNailView.

A view which can be used to display YouTube thumbnails, either for a specific YouTube video or a YouTube playlist.

To get started, place this view in your view hierarchy and call initialize(String, OnInitializedListener) to create a YouTubeThumbnailLoader which you can use to load YouTubeThumbnails into this View. Thumbnail is nothing but the image of that corresponding video to show a glimpse to user. This image is auto generated which comes from the server. Now we have a play button, need click to start that video. To start the video, we need this code:

Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) ctx,
        Resources.KEY,
        VideoID[getLayoutPosition()],//video id
        100,     //after this time, video will start automatically
        true,               //autoplay or not
        false);             //lightbox mode or not; show the video in a small box
ctx.startActivity(intent);

This will start video automatically after 100ms.

Step-04:

Connect the adapter with your RecyclerView component. My code is given below:

public class RecyclerActivity extends Activity {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.recycler_main);
        RecyclerView recyclerView=(RecyclerView)findViewById(R.id.list);
        recyclerView.setHasFixedSize(true);
        //to use RecycleView, you need a layout manager. default is LinearLayoutManager
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        RecyclerAdapter adapter=new RecyclerAdapter(RecyclerActivity.this);
        recyclerView.setAdapter(adapter);
    }
}

Main layout for activity is here:

<?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">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>