How to play youtube video on fragment in Android

Posted By : Piyush Dubey | 19-Jun-2017


Today I am going to write blog on how to play youtube videos on fragment using YouTubePlayerSupportFragment.

Following steps are needed to achieve this task:

1.  First of all provide internet access permission in android manifest file.

2.  Then move on to developer console and select your project or create new project.

3.  Then click on Enable API tab and enable from list the YouTube Data API v3 API.

4.  Then Create the API Key for this project to use the enabled api by clicking on Credential
     and providing the rquired information.

5.   Then move to https://developers.google.com/youtube/android/player/downloads/ and downlod the
      YoutubeAndroidPlayerApi jar.

6.   Then Include your YoutubeAndroidPlayerApi jar in your project inside the libs package and then
       right clicking on it and add it as a library.

7.   Design a layout of fragment which include YouTubePlayerSupportFragment.

8.   Create an instance of YouTubePlayerSupportFragment in the fragment.

9.   Add layout of your fragment to YouTubePlayerSupportFragment using fragmentmanager and fragment transactions.

10. Initialize the instance of YouTubePlayerSupportFragment using created API key and interface YouTubePlayer.OnInitializedListener.

11. Then on the callback method onInitializationSuccess you will get the object of youtubeplayer.

12.  Now you can play the youtube video by using youTubePlayer.loadVideo("youtubevideoId") or youTubePlayer.cueVideo("youtubevideoId"),
       where youtubevideoid is the id of your youtube video.

   Complete implementation of the code can be found here: https://github.com/piyushdubey529/youtubeplayerfragment

 

THANKS

About Author

Author Image
Piyush Dubey

Piyush is a good learner & innovative. He is passionate about coding and likes to watch cricket & listening music. He has worked on projects like ZipPosRepots, ZipOrdering.

Request for Proposal

Name is required

Comment is required

Sending message..