YouTube has an official Player API for Android, to play videos in a native player. But this API has a few limitations, as explained in this post. The best way to go around those limitations is to play YouTube videos inside a WebView. By using a WebView you will have a simple View that can be added anywhere in your app. It will be much easier to use than the native player API and you won’t have to deal with its bugs and issues.

But you can’t just load a page from YouTube in your WebView. Otherwise your app will be just a web browser with a bad user experience. The best way to play YouTube videos on the web is to use the IFrame Player API, from YouTube. This is a Javascript API that gives access to a nice web-based YouTube player.

To use it in your app you need to write a web page and then load that page in a WebView. But now you have some extra work to do, how do you interact with the web page from your Android code? The way to do this is to write a Javascript interface, that gets injected inside the WebView and creates a bridge between the Android world (Java/Kotlin) and the web world (Javascript).

This is a lot of work if you just need to play a YouTube video. I had to do it once for one of my apps and, to avoid the time investment to other people, I decided to opensource it as a library.

The library is called android-youtube-player, it is an API to play YouTube videos inside of Android WebViews, in a way that feels natural and effortless to the developer. You won’t have to write any web pages or Javascript code.

The player provided by the library is highly customizable and is meant to be used a replacement to both the official native API and the hacky WebView solution.

To use it, just add it to your project dependencies.

Add the YouTubePlayerView to your layout.xml file.

By setting the “useWebUi” attribute to true, the player will use the web-based UI of the IFrame Player API. Instead of the native UI provided by the library.

web-based UI

The second and last step you need, is to get a reference to the AndroidYouTubePlayerView in your Activity or Fragment and add it as a LifecycleObserver.

Now you have a YouTube video playing inside of a WebView in your app.

—

If you need more control, you can add a YouTubePlayerListener to a YouTubePlayerView to start reacting to events from your video and to interact with the player.

There is no easier way to play YouTube videos in a WebView.

Next steps