Home » Android » How to use YoutubePlayerView in fragment

How to use YoutubePlayerView in fragment

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am trying to play youtube video in youtubePlayerView inside Navigation drawer, in fragment.But not not able to, please help me out in this.

Answers:
<fragment
  android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
  android:id="@+id/youtube_fragment"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"/>


and in fragment onCreateView

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_you_tube_api, container, false);

        YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();

        youTubePlayerFragment.initialize("DEVELOPER_KEY", new OnInitializedListener() {

            @Override
            public void onInitializationSuccess(Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
                if (!b) {
                    YPlayer = youTubePlayer;
                    YPlayer.setFullscreen(true);
                    YPlayer.loadVideo("2zNSgSzhBfM");
                    YPlayer.play();
                }
            }

            @Override
            public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
                // TODO Auto-generated method stub

            }
        });

    }