Thursday, 13 November 2014

how to paly youtube video for webview in andriod example

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical" >

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

</LinearLayout>


MainActivity.java


public class MainActivity extends Activity {

WebView mWebView;

       @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

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

/** unfortunately, we have to check sdk version ***/
        if (Build.VERSION.SDK_INT < 8) {
            mWebView.getSettings().setPluginsEnabled(true);
        } else {
            mWebView.getSettings().setPluginState(PluginState.ON);
        }
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setUserAgent(0);
        mWebView.setWebChromeClient(new WebChromeClient() {
        });


        /**
         * <iframe id="ytplayer" type="text/html" width="640" height="360"
         * src="https://www.youtube.com/embed/WM5HccvYYQg" frameborder="0"
         * allowfullscreen>
         **/


 String html = "<iframe class=\"youtube-player\" "
         + "style=\"border: 0; width: 100%; height: 95%;"
         + "padding:0px; margin:0px\" "
         + "id=\"ytplayer\" type=\"text/html\" "
         + "src=\"//www.youtube.com/embed/" + videoId
         + "?fs=1\" frameborder=\"0\" " + "allowfullscreen autobuffer "
         + "controls onclick=\"this.play()\">\n" + "</iframe>\n";


        final String mimeType = "text/html";
        final String encoding = "UTF-8";                                  

        mWebView.loadDataWithBaseURL("", html, mimeType, encoding, "");

   }
}

AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET" />

 <application
        android:allowBackup="true"

        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

</application>



No comments:

Post a Comment