Sunday, June 30, 2013

Example to use YouTubePlayerFragment of YouTube Android Player API

Example to use YouTubePlayerFragment of YouTube Android Player API

Example to use YouTubePlayerFragment of YouTube Android Player API


Follow the step in "YouTube Android Player API step-by-step" to Download and import YouTube Android Player API, and Register your app using YouTube Android Player API and obtain API Key. To use YouTubePlayerFragment, you have to define android:minSdkVersion="11" or higher in your AndroidManifest.xml.

Modify /res/layout/activity_main.xml to define layout, with <fragment> of "com.google.android.youtube.player.YouTubePlayerFragment".
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <fragment
        android:name="com.google.android.youtube.player.YouTubePlayerFragment"
        android:id="@+id/youtubeplayerfragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold"
        android:layout_gravity="center_horizontal"
        android:autoLink="web" />
    
    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:id="@+id/btnviewfullscreen"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="View in Full Screen" />
            <TextView 
                android:id="@+id/videolog"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            
        </LinearLayout>
    </ScrollView>
    
</LinearLayout>


Create /res/layout-land/activity_main.xml to define layout in Landscape orientation.
<LinearLayout 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"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <fragment
        android:name="com.google.android.youtube.player.YouTubePlayerFragment"
        android:id="@+id/youtubeplayerfragment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"/>
    <LinearLayout 
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="http://android-er.blogspot.com/"
            android:textStyle="bold"
            android:layout_gravity="center_horizontal"
            android:autoLink="web" />
        
        <ScrollView 
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <LinearLayout 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <Button
                    android:id="@+id/btnviewfullscreen"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="View in Full Screen" />
                <TextView 
                    android:id="@+id/videolog"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
  </ScrollView>
    </LinearLayout>
</LinearLayout>


MainActivity.java
package com.example.androidyoutubeapiplayer;

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.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends YouTubeBaseActivity implements 
 YouTubePlayer.OnInitializedListener{
 
 public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
 public static final String VIDEO_ID = "o7VVHhK9zf0";
 
 private YouTubePlayer youTubePlayer;
 private YouTubePlayerFragment youTubePlayerFragment;
 private TextView textVideoLog;
 private Button btnViewFullScreen;
 
 private static final int RQS_ErrorDialog = 1;
 
 private MyPlayerStateChangeListener myPlayerStateChangeListener;
 private MyPlaybackEventListener myPlaybackEventListener;
 
 String log = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
             .findFragmentById(R.id.youtubeplayerfragment);
        youTubePlayerFragment.initialize(API_KEY, this);

        textVideoLog = (TextView)findViewById(R.id.videolog);
        
        myPlayerStateChangeListener = new MyPlayerStateChangeListener();
        myPlaybackEventListener = new MyPlaybackEventListener();
        
        btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
        btnViewFullScreen.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    youTubePlayer.setFullscreen(true);
   }});
    }

 @Override
 public void onInitializationFailure(Provider provider,
   YouTubeInitializationResult result) {
  
  if (result.isUserRecoverableError()) {
   result.getErrorDialog(this, RQS_ErrorDialog).show(); 
  } else {
   Toast.makeText(this, 
     "YouTubePlayer.onInitializationFailure(): " + result.toString(), 
     Toast.LENGTH_LONG).show(); 
  }
 }

 @Override
 public void onInitializationSuccess(Provider provider, YouTubePlayer player,
   boolean wasRestored) {
  
  youTubePlayer = player;
  
  Toast.makeText(getApplicationContext(), 
    "YouTubePlayer.onInitializationSuccess()", 
    Toast.LENGTH_LONG).show();
  
  youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
  youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);
  
  if (!wasRestored) {
        player.cueVideo(VIDEO_ID);
      }

 }
 
 private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
  
  private void updateLog(String prompt){
   log +=  "MyPlayerStateChangeListener" + "\n" + 
     prompt + "\n\n=====";
   textVideoLog.setText(log);
  };

  @Override
  public void onAdStarted() {
   updateLog("onAdStarted()");
  }

  @Override
  public void onError(
    com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
   updateLog("onError(): " + arg0.toString());
  }

  @Override
  public void onLoaded(String arg0) {
   updateLog("onLoaded(): " + arg0);
  }

  @Override
  public void onLoading() {
   updateLog("onLoading()");
  }

  @Override
  public void onVideoEnded() {
   updateLog("onVideoEnded()");
  }

  @Override
  public void onVideoStarted() {
   updateLog("onVideoStarted()");
  }
  
 }
 
 private final class MyPlaybackEventListener implements PlaybackEventListener {
  
  private void updateLog(String prompt){
   log +=  "MyPlaybackEventListener" + "\n-" + 
     prompt + "\n\n=====";
   textVideoLog.setText(log);
  };

  @Override
  public void onBuffering(boolean arg0) {
   updateLog("onBuffering(): " + String.valueOf(arg0));
  }

  @Override
  public void onPaused() {
   updateLog("onPaused()");
  }

  @Override
  public void onPlaying() {
   updateLog("onPlaying()");
  }

  @Override
  public void onSeekTo(int arg0) {
   updateLog("onSeekTo(): " + String.valueOf(arg0));
  }

  @Override
  public void onStopped() {
   updateLog("onStopped()");
  }
  
 }

}

download filesDownload the files.

Download APK to try on your device.



The tutorial: YouTube Android Player API step-by-step

4 comments:

Unknown said...

Dude this is not fragment, this is still activity!

nptriet said...

i think "fragment" here is

not like your thinking

Ekansh Rastogi said...

Fake article, why man why ?? Just keeing view in fragment does not make it a fragment. You still do every thing in activity.

Anonymous said...

load youtube fragment in another fragment(not activity) is what expected!!!