Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Play Youtube Video in Fragment Using YouTubePlayerFragment

    • 0
    • 0
    • 0
    • 0
    • 5
    • 0
    • 1
    • 0
    • 6.08k
    Comment on it

    This tutorial explain how we can Play YouTube video within Fragment.
     

    1. Create simple Fragment class extending Fragment.

    2. Implement YouTubePlayer.OnInitializedListener to Fragment and override its methods.

    3. Create FrameLayout in Layout file of Fragment. like below:-
     

    <FrameLayout 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"
        tools:context="com.ammy.youtubesample.MainFragment">
    
        <FrameLayout
            android:id="@+id/frame_fragment"
            android:layout_width="match_parent"
            android:layout_height="200dp"></FrameLayout>
    
    </FrameLayout>
    

     

    4. In Fragment Java class Create YouTubePlayerFragment instance and replace this fragment with framelayout like below:
     

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view =  inflater.inflate(R.layout.fragment_main, container, false);
    
            YouTubePlayerFragment youtubePlayerFragment = new YouTubePlayerFragment();
            youtubePlayerFragment.initialize(getString(R.string.api_key), this);
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frame_fragment, youtubePlayerFragment);
            fragmentTransaction.commit();
    
    
            return view;
        }

     

    5.  Check initialization of youTube in listener's method and play video.
     

     @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
            if(!b){
                youTubePlayer.cueVideo("EJylz_9KYf8");
            }
        }
    
        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
            Toast.makeText(getActivity(),"fail",Toast.LENGTH_SHORT).show();
    
        }

     

    Enjoy.
    Happy Coding... ;)

    Play Youtube Video in Fragment Using YouTubePlayerFragment

 5 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: