Easy Tutorial step by step with free source code: Play YouTube Video using YouTube Player Fragment with YouTube Android Player API in Android Studio version 2.1.2.
Learn how to download and import YouTube Android Player API.
Create new project with Application name: YouTube Player Fragment; Minimum SDK: API 11 – Android 3.0 (Honeycomb).

Download YouTube Android Player API: https://developers.google.com/youtube/android/player/downloads/
Copy YouTubeAndroidPlayerApi.jar library file in your /libs folder of project (e.g. C:\Users\Your-User-Name\AndroidStudioProjects\YouTubePlayerFragment\app\libs\YouTubeAndroidPlayerApi.jar).

In manifest->AndroidManifest.xml write the code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.toyo.youtubeplayerfragment"
android:installLocation="preferExternal">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

In app->res->layout->activity_main.xml write the code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.app.toyo.youtubeplayerfragment.MainActivity">
    <fragment
        android:name="com.google.android.youtube.player.YouTubePlayerFragment"
        android:id="@+id/youtubeplayerfragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

In app->java->MainActivity.java write the code:

package com.app.toyo.youtubeplayerfragment;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.Toast;
import android.content.Intent;
public class MainActivity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "YOUR API KEY";
private static final String VIDEO_ID = "YOUR VIDEO ID";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerFragment myYouTubePlayerFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
"There was an error initializing the YouTubePlayer (%1$s)",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
}

Obtain your API Key from Google APIs: https://code.google.com/apis/console (e.g. AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA).
Get your Video ID from YouTube (e.g. R4x-0ZKW-Pk).

Run app in mobile device and watch video from YouTube in format portrait, landscape and full screen with option of changing Quality of video.

Emulator can’t play YouTube videos, because YouTube have different formats (avi, mp4, mov, wmv etc) than emulator which supports only 3gp videos.

Follow Video Tutorial How to Play YouTube VIDEO using YouTube Player Fragment with YouTube Android Player API:

If you want to load an Playlist instead of Video from YouTube, in MainActivity.java change cueVideo(VIDEO_ID) with cuePlaylist(PlayList_ID) and get your Playlist ID from YouTube (e.g. PL1LAkZ-M7pNKwicHAlI3HGQMH0jofeXmd) :

Tutorial YouTube Playlist Fragment

Download free YouTube-Fragment.apk application and install it on your mobile device to see how it works:
http://android-coffee.com/wp-content/uploads/projecs/youtube-fragment.apk

Please subscribe here to our YouTube channel. Thank you!
Check next tutorials to learn all about Android.
For further questions leave a message.

2 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

Ok, so where did you play a YouTube video in a Fragment? This is playing it in an Activity. How does one go about doing this in a Fragment?

Many thanks

Hi Sir,

Your tutorial is great. Please make the same project in ‘Master List Detail Flow’ type activity in which we have list of videos and when we click on video from list it will go that particular video. Thank you for the tutorials.

Best regards,
Faisal

Leave a Reply

Your email address will not be published. Required fields are marked *

Blue Captcha Image Refresh

*