Android WebView Tutorial

Android WebView Tutorial – WebView Example

WebView:WebView is a view used to display the web pages in application. This class is the basis upon which you can roll your own web browser or simply use it to display some online content within your Activity. We can also specify HTML string and can show it inside our application using a WebView. Basically, WebView turns application into a web application.

Step 1: Open up Android Studio Project through res -> layout -> activity_main.xml (or) main.xml and add below code or just drag and drop the switch to design XML file.

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <WebView
        android:id="@+id/simpleWebView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="20dp"
        android:scrollbars="none" />

</LinearLayout>

Step 2: Add below code in MainActivity.java.

package com.bytelogs.exaample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ButtonBarLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    WebView WebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        WebView = (WebView) findViewById(R.id.simpleWebView);
         WebView.setWebViewClient(new MyWebViewClient());
                String url = "http://bytelogs.com";
                WebView.getSettings().setJavaScriptEnabled(true);
                WebView.loadUrl(url); // load a web page in a we

    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    
}