fireball.1
fireball.1

Reputation: 1521

How to play a YouTube video in a fragment in Android?

I am creating an app on api29 and trying to implement different kinds of fragments. I have a :

I have also downloaded v1.2.2 of youtube API and placed the jar in the lib folder of my application and added internet access to the manifest file.

However, I am not sure on how to proceed and where to actually code

and what exactly to code

Upvotes: 0

Views: 239

Answers (1)

MohammadAli
MohammadAli

Reputation: 3456

  • how to proceed and where to actually code

    You want to code in VideoFragment

  • what exactly to code:

    Please follow this link: YouTube Android Player API

  • a videoview or something altogether new

    First add jar dependency implementation files('libs/YouTubeAndroidPlayerApi.jar')

Now user below code in xml:

<com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player_view"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_200sdp"
        android:layout_margin="@dimen/_5sdp"
        android:layout_below="@+id/header"
        />

Java code:

youtube_player_view = findViewById(R.id.youtube_player_view);

private void initVideo(final String videoId) {
        youtube_player_view.initialize(getResources().getString(R.string.youtube_api_key), new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean youtube_avalable) {
                //youTubePlayerMain = youTubePlayer;

                if (!youtube_avalable) {

                    youTubePlayerMain = youTubePlayer;

                    youTubePlayerMain.loadVideo(videoId);
                    youTubePlayerMain.setShowFullscreenButton(false);
                }
            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
                if (youTubeInitializationResult.isUserRecoverableError()) {
                    youTubeInitializationResult.getErrorDialog(getApplicationContext(), 1).show();
                } else {
                    Toast.makeText(getApplicationContext(), youTubeInitializationResult.toString(), Toast.LENGTH_LONG).show();
                }
            }
        });

    }

Upvotes: 2

Related Questions