How To Embed YouTube Video In Android WebView

How-To-Embed-YouTube-Video-In-Android-WebView-Thumb

24th February, 2020

Hey Android developer, In this tutorial you will learn how to Embed and Play YouTube Video in Android WebView.

Step 1: Add Internet Permission

This application requires an internet connection to play YouTube video. So, first you need to add Internet access permission in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.codestringz.testapp">
    
    <!--Internet permission-->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        ...
		...>
    </application>

</manifest>

Step 2: Set Up WebView in Layout XML

Now set up the WebView in Activity Layout XML file. This WebView will load your YouTube video.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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=".MainActivity">

    <WebView
        android:id="@+id/mWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Step 3: Load YouTube Video From Activity

To load YouTube video, Modify the activity as follows.

package com.codestringz.testapp;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity
{

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String myYouTubeVideoUrl = "https://www.youtube.com/embed/XUTXU6fy94E";

        String dataUrl =
                "<html>" +
                    "<body>" +
                        "<h2>Video From YouTube</h2>" +
                        "<br>" +
                        "<iframe width=\"560\" height=\"315\" src=\""+myYouTubeVideoUrl+"\" frameborder=\"0\" allowfullscreen/>" +
                    "</body>" +
                "</html>";

        WebView myWebView = findViewById(R.id.mWebView);

        WebSettings webSettings = myWebView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        myWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        myWebView.getSettings().setLoadWithOverviewMode(true);
        myWebView.getSettings().setUseWideViewPort(true);
        myWebView.loadData(dataUrl, "text/html", "utf-8");
    }
}

Output: Video Demo

Happy coding!

Leave a Reply