Skip to content

Instantly share code, notes, and snippets.

@takeshiyako2
Last active May 29, 2023 15:48
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save takeshiyako2/e776bbaf2966c6501c4f to your computer and use it in GitHub Desktop.
Save takeshiyako2/e776bbaf2966c6501c4f to your computer and use it in GitHub Desktop.
Android Sample YouTube API on the Fragment
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/main"
tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxxx.xxxx.xxxx.fragmentdeyoutube" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "xxxx.xxxx.xxxx.fragmentdeyoutube"
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
compile files('libs/YouTubeAndroidPlayerApi.jar')
}
package xxxx.xxxx.xxxx.fragmentdeyoutube;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// フラグメント起動 (v4の作法で)
YoutubeFragment fragment = new YoutubeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.main, fragment)
.addToBackStack(null)
.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/youtube_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:visibility="visible" />
</RelativeLayout>
package xxxx.xxxx.xxxx.fragmentdeyoutube;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.OnInitializedListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
public class YoutubeFragment extends Fragment {
// API キー
private static final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// YouTubeのビデオID
private static String VIDEO_ID = "EGy39OMyHzw";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.you_tube_api, container, false);
// YouTubeフラグメントインスタンスを取得
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
// レイアウトにYouTubeフラグメントを追加
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();
// YouTubeフラグメントのプレーヤーを初期化する
youTubePlayerFragment.initialize(API_KEY, new OnInitializedListener() {
// YouTubeプレーヤーの初期化成功
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
player.loadVideo(VIDEO_ID);
player.play();
}
}
// YouTubeプレーヤーの初期化失敗
@Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
// YouTube error
String errorMessage = error.toString();
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
Log.d("errorMessage:", errorMessage);
}
});
return rootView;
}
}
@dvaibhavd
Copy link

getting error on yourfragment.java on line 34
cannot convert youtubesupportfragment to fragment

@lmichailian
Copy link

I got this error A YouTubePlayerView can only be created with an Activity which extends YouTubeBaseActivity

@DeveloperMarius
Copy link

How can i add the PlaybackEventListener and PlayerStateChangeListener?

@ajdeguzman
Copy link

Hi MariusDev7, you can add it by implementing it this way:

public class Sample extends Fragment implements YouTubePlayer.OnInitializedListener, YouTubePlayer.PlaybackEventListener, YouTubePlayer.PlayerStateChangeListener

and inside onInitializationSuccess:

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
        player.setPlaybackEventListener(this);
        player.setPlayerStateChangeListener(this);
}

@quangthanhvo
Copy link

When I press back, fragment youtube closed but I wanted when press back activity closed

Copy link

ghost commented Dec 16, 2016

Everything work fine but video pause after 1 second. My fragment layout like below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:fab="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
     .
     .
     .
    </LinearLayout>
   <FrameLayout
        android:id="@+id/youtube_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:visibility="visible" />
  <android.support.v7.widget.RecyclerView
       android:id="@+id/content_recycle_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

My error is

YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor android.support.v4.view.ViewPa

@JitanderVerma
Copy link

You Saved my life man. Thank You.. Alott. :)

Copy link

ghost commented Jan 26, 2017

Once properly placed components(RecycleView, ViewPage and etc...) in layout, problem is solved. Thanks

@degendra
Copy link

@quangthanhvo
Remove this line from MainActivity.java. .addToBackStack(null)

@yasriady
Copy link

Excellent guys, you saved my life... thank you anyway ....

@shadowkane
Copy link

shadowkane commented Dec 7, 2017

i wrote this just to tell you, thank you so much, you are the best.
the only code that helps me out,
the rest of them was using activity and they call it fragment, the only one use a real fragment was you,
you rock, keep going

@ebartan
Copy link

ebartan commented Feb 17, 2018

YoutubeFragment.java is useful thx

@kemalturk
Copy link

This is very helpful.Thank you.

@nick-bigger
Copy link

Thank you! This was incredibly helpful, and the only information I could find on using the YouTube API in a fragment.

@Asmanjas
Copy link

thank you :)

@ludwigjer
Copy link

thank you so much, I have no words but thank you !

@Alkahirah
Copy link

`YouTubePlayerSupportFragment youTubePlayFragment=YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction=getChildFragmentManager().beginTransaction();

        transaction.add(R.id.youtube_fragment, youTubePlayFragment).commit();  \\ My Error here


        youTubePlayFragment.initialize(YoutubeDeveloperKey, new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

                if (!b)
                {
                    System.out.println("In The success");
                    YPlayer = youTubePlayer;
                    YPlayer.setFullscreen(true);
                    YPlayer.cueVideo(VIDEO_ID);
                    YPlayer.play();
                }

            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
                if (errorReason.isUserRecoverableError()){
                    System.out.println("In The Failure");
                    errorReason.getErrorDialog(getActivity(),1).show();

                }
                else {
                    String errorMessage=String.format("Ther was wrror initioslksd the ",errorReason.toString());
                    System.out.println(errorMessage);
                }
            }
        });

`
I have an error that when I wrote ' transaction.add(R.id.youtube_fragment, youTubePlayFragment).commit();' Red underline apear in this ststment
and said
Ashampoo_Snap_2020 02 08_10h02m48s_001_

@gavriel347
Copy link

yo te amo culero, gracias por el aporte

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment