In previous article we learnt how to play a youtube video in android using YoutubePlayerView and using YoutubeBaseActivity.
But there is one problem in YoutubePlayerView that we need to extend our activity with YoutubeBaseActivity. What if we don’t want to extend our activity with YoutubeBaseActivity or we want to implement the YoutubePlayerView in fragment.
There is a solution for the above problem i.e YoutubePlayerFragment. A fragment that contains a YouTubePlayerView. Using this fragment is the preferred way of playing YouTube videos because your activity does not need to extend an activity provided by the library, as is the case with using the YouTubePlayerView directly.
So today we are going to work on the same only and we will see how to implement the YoutubePlayerFragment and play our video.
Before starting this article please go through to the previous article about YoutubePlayer and do the below mentioned tasks:
1. Create the project in google console and get the Developer key.
2. Add then download the YoutubePlayerAPI jar file and add into your project.
1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. These are some strings that we are going to use in our project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<resources> <string name="app_name">Youtube Player Fragment Demo</string> <string name="thumbnail_image_view_desc">Youtube Video thumbnail image view</string> <!-- we need to use video ids instead of video link --> <string-array name="video_id_array"> <item>CqhpNxI8qYw</item> <item>sasCrpgHDy8</item> <item>iJeh3x09Ya8</item> <item>B5zRaD7B504</item> <item>9qWHzj8k-Uo</item> <item>RjiK45wC924</item> <item>RH3zaLO8H4E</item> <item>o14pyzosjvk</item> <item>5SQrpBQne7A</item> <item>5WJ3r67ORxo</item> </string-array> </resources> |
3. So before getting started you need to download the jar file of Youtube Android Player API. Download the jar file and add into your project dependency. After adding jar to dependency the gradle will look like below:
1 2 3 4 5 6 7 8 9 |
dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:27.0.0' implementation 'com.android.support:cardview-v7:27.0.0' implementation 'com.android.support:recyclerview-v7:27.0.0' //Youtube Android Player API Jar dependency implementation project(':YouTubeAndroidPlayerApi') } |
4. Now open your activity_main.xml and add the below code to it. In this class add the com.google.android.youtube.player.YouTubePlayerSupportFragment as fragment and one RecyclerView to display the list of videos in horizontal direction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.youtubeplayerfragmentdemo.main.MainActivity"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:minHeight="?attr/actionBarSize" app:title="@string/app_name" app:titleTextColor="@android:color/white" /> <!-- Youtube Player Fragment --> <fragment android:id="@+id/youtube_player_fragment" android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/recycler_view" android:layout_below="@+id/toolbar" /> <!-- RecyclerView to display list of Videos in Horizontal direction --> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentBottom="true" android:paddingEnd="10dp" android:paddingRight="10dp" /> </RelativeLayout> |
5. Now open your MainActivity.java and add the below code to it. In this class we need to find the id of YoutubePlayerFragment and initialise the YoutubePlayer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
package com.youtubeplayerfragmentdemo.main; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerSupportFragment; import com.youtubeplayerfragmentdemo.utils.Constants; import com.youtubeplayerfragmentdemo.R; import com.youtubeplayerfragmentdemo.utils.RecyclerViewOnClickListener; import com.youtubeplayerfragmentdemo.adapter.YoutubeVideoAdapter; import java.util.ArrayList; import java.util.Collections; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private RecyclerView recyclerView; //youtube player fragment private YouTubePlayerSupportFragment youTubePlayerFragment; private ArrayList<String> youtubeVideoArrayList; //youtube player to play video when new video selected private YouTubePlayer youTubePlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); generateDummyVideoList(); initializeYoutubePlayer(); setUpRecyclerView(); populateRecyclerView(); } /** * initialize youtube player via Fragment and get instance of YoutubePlayer */ private void initializeYoutubePlayer() { youTubePlayerFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager() .findFragmentById(R.id.youtube_player_fragment); if (youTubePlayerFragment == null) return; youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { youTubePlayer = player; //set the player style default youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); //cue the 1st video by default youTubePlayer.cueVideo(youtubeVideoArrayList.get(0)); } } @Override public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) { //print or show error if initialization failed Log.e(TAG, "Youtube Player View initialization failed"); } }); } /** * setup the recycler view here */ private void setUpRecyclerView() { recyclerView = findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); //Horizontal direction recycler view LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); } /** * populate the recycler view and implement the click event here */ private void populateRecyclerView() { final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList); recyclerView.setAdapter(adapter); //set click event recyclerView.addOnItemTouchListener(new RecyclerViewOnClickListener(this, new RecyclerViewOnClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (youTubePlayerFragment != null && youTubePlayer != null) { //update selected position adapter.setSelectedPosition(position); //load selected video youTubePlayer.cueVideo(youtubeVideoArrayList.get(position)); } } })); } /** * method to generate dummy array list of videos */ private void generateDummyVideoList() { youtubeVideoArrayList = new ArrayList<>(); //get the video id array from strings.xml String[] videoIDArray = getResources().getStringArray(R.array.video_id_array); //add all videos to array list Collections.addAll(youtubeVideoArrayList, videoIDArray); } } |
6. For RecyclerView item row create new xml layout naming youtube_video_custom_layout.xml and add the YoutubeThumbnailView to it inside CardView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:id="@+id/youtube_row_card_view" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" app:cardCornerRadius="4dp" app:contentPadding="10dp"> <!-- youtube thumbnail view to show the thumbnail of videos --> <com.google.android.youtube.player.YouTubeThumbnailView android:id="@+id/video_thumbnail_image_view" android:layout_width="120dp" android:layout_height="120dp" android:background="@android:color/darker_gray" android:contentDescription="@string/thumbnail_image_view_desc" android:scaleType="centerCrop" /> </android.support.v7.widget.CardView> |
7. Now create adapter for RecyclerView naming YoutubeVideoAdapter.java and add the below code to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
package com.youtubeplayerfragmentdemo.adapter; import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubeThumbnailLoader; import com.google.android.youtube.player.YouTubeThumbnailView; import com.youtubeplayerfragmentdemo.R; import com.youtubeplayerfragmentdemo.holder.YoutubeViewHolder; import com.youtubeplayerfragmentdemo.utils.Constants; import java.util.ArrayList; /** * Created by sonu on 10/11/17. */ public class YoutubeVideoAdapter extends RecyclerView.Adapter<YoutubeViewHolder> { private static final String TAG = YoutubeVideoAdapter.class.getSimpleName(); private Context context; private ArrayList<String> youtubeVideoModelArrayList; //position to check which position is selected private int selectedPosition = 0; public YoutubeVideoAdapter(Context context, ArrayList<String> youtubeVideoModelArrayList) { this.context = context; this.youtubeVideoModelArrayList = youtubeVideoModelArrayList; } @Override public YoutubeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.youtube_video_custom_layout, parent, false); return new YoutubeViewHolder(view); } @Override public void onBindViewHolder(YoutubeViewHolder holder, final int position) { //if selected position is equal to that mean view is selected so change the cardview color if (selectedPosition == position) { holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary)); } else { //if selected position is not equal to that mean view is not selected so change the cardview color to white back again holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, android.R.color.white)); } /* initialize the thumbnail image view , we need to pass Developer Key */ holder.videoThumbnailImageView.initialize(Constants.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) { //when initialization is sucess, set the video id to thumbnail to load youTubeThumbnailLoader.setVideo(youtubeVideoModelArrayList.get(position)); youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() { @Override public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) { //when thumbnail loaded successfully release the thumbnail loader as we are showing thumbnail in adapter youTubeThumbnailLoader.release(); } @Override public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) { //print or show error when thumbnail load failed Log.e(TAG, "Youtube Thumbnail Error"); } }); } @Override public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) { //print or show error when initialization failed Log.e(TAG, "Youtube Initialization Failure"); } }); } @Override public int getItemCount() { return youtubeVideoModelArrayList != null ? youtubeVideoModelArrayList.size() : 0; } /** * method the change the selected position when item clicked * @param selectedPosition */ public void setSelectedPosition(int selectedPosition) { this.selectedPosition = selectedPosition; //when item selected notify the adapter notifyDataSetChanged(); } } |
8. Don’t forget to give Internet permission in your AndroidManifest.xml file else your app will not run.
1 |
<uses-permission android:name="android.permission.INTERNET" /> |
9. Finally all done, now you can also play video in your app without using YoutubeBaseActivity.
Thanks.
Subscribe to us and get the latest news.
14 Comments
Archana
Sunday, February 25th, 2018I added my own api key and try to run this code but getting error like “An error occurred while initializing the youtube player”
Dr. Droid
Wednesday, February 28th, 2018Hi Archana
Can you tell me does your project at Google console has YouTube Data API enbaled?
Does your manifest has INTERNET permission?
Thanks
Mityo
Thursday, December 27th, 2018It works with No problems!!!
Emil
Friday, December 28th, 2018I have been struggling to use this app on a android tv box, but I am unable to click or play any of the videos with the remote. It only works on a phone. I have tried many ways but it doesn’t seem to work. Please help.
Dr. Droid
Friday, December 28th, 2018Hi Emil,
I don’t have any idea about TV Box as i haven’t tried it.
Actually the app is only for mobile so i think it wont work on TV.
Thanks.
Slava
Friday, March 22nd, 2019Hi, Dr.Droid!
I have not understand, where is realisation of YoutubeViewHolder in adapter, and why I have not can use RecyclerView OnClickListener in Main class
Slava
Friday, March 22nd, 2019Hi!
I have not understand, how and where you has realisation of YoutubeViewHolder in adapter, and why I have not can use RecyclerView OnClickListener in Main class
Dr. Droid
Saturday, March 23rd, 2019Hi Slava,
Download the source code to get all the classes. I have pasted only classes which are important.
Thanks
Priyanka
Thursday, May 28th, 2020Hi, Dr.Droid!
How can we play youtube videos in RecyclerView only?
summyia
Saturday, September 12th, 2020how can we implement JSON fetched list of youtube videos in this? I am working on it but its giving errors
summyia
Saturday, September 12th, 2020this code worked perfect for manually adding video list. But how can we implement JSON fetched list of youtube videos in this? I am working on it but its giving errors
Dr. Droid
Wednesday, September 16th, 2020Hi Summyia,
Can you share the error which you are getting?
Thanks
SoCu
Saturday, August 20th, 2022Hi, Dr.Droid!
It seems that it is no longer usable with androidx, it shows me the following error: “Inconvertible types; cannot cast ‘androidx.fragment.app.Fragment’ to ‘com.google.android.youtube.player.YouTubePlayerSupportFragment” hay alguna solucion
Dr. Droid
Wednesday, August 24th, 2022Hi SoCu,
You need to migrate the project to androidX to make it work. As this project is very old.
Thanks