Skip to main content

Android WebView

WebView is used to display web pages in your application. Basically, it helps to build your own browser so that you can show online content in your application.
Let's take an example where we will open this blog in our application 
1. Create a new android project.
2. Open AndroidManifest.xml and add uses permission-
<uses-permission android:name="android.permission.INTERNET" />
3. Open activity_main.xml and add a webView in it's layout to render codemodeweb.blogspot.in
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.gunjan.andriodcodesnippets.MainActivity">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/web_view"></WebView>
</RelativeLayout>
4. Open MainActivity.java and add the following code-
package com.gunjan.andriodcodesnippets;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {

    //Declare webView member
    private WebView myWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        myWebView=(WebView)findViewById(R.id.web_view);
        
        //Load url into webView. You could add any url
        myWebView.loadUrl("https://codemodeweb.blogspot.in/");
        
        //Set webViewClient to show webpage on your app 
        myWebView.setWebViewClient(new WebViewClient());
        
        myWebView.getSettings().setJavaScriptEnabled(true);
    }
}
5. Run the project.

Comments

  1. Great post. I was checking constantly this blog and I am impressed!

    Very useful information specially the last part :) I care for such information a lot.
    I was looking for this particular information for a long time.
    Thank you and good luck.

    ReplyDelete

Post a Comment

Popular Posts