WebView in Android

Share this

In this tutorial we will see how open url within app with help of WebView.
this is used like custom browser.

Lets get started.
1. Open android studio
2. Create a new project
3. Set application name WebView
4. I used package path as com.androidcodr.webview click next.
5. On this screen set minimum sdk API 16 click next.
6. Add empty activity. click next.
7. Keep Activity name as MainActivity click finish. wait till project load completely.
8. Goto activity_main.xml
9. If you are having constrainLayout change it to RelativeLayout.
Just replace android.support.constraint.ConstraintLayout with RelativeLayout

10. Delete Hello world textview.

11. Now drag n drop WebView from palette
set its property as follows

 

   <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" >
    </WebView>

12. We will add progressbar to know our web page is loading.
and hide it when page is loaded completely.

13. add ProgressBar at the centre of webview.

set its property as follows

 

 <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        style="?android:attr/progressBarStyle"
        android:visibility="gone" />

Here we set visibility gone.

14. now add code fot it in MainActivity.java

15. Declare

    private WebView myweb;
    private ProgressBar loading;

16. Initialize in OnCreate Method.

 

        myweb = (WebView) findViewById(R.id.webview);
        loading = (ProgressBar) findViewById(R.id.progressBar);

17. To view and work website properly. we must enable javascript of webview.

     myweb.getSettings().setJavaScriptEnabled(true); 

18. now add url which you want to open in loadUrl method of webview as follow.

 

    myweb.loadUrl("http://www.androidcodr.com");

18. We will define Inner class and set it as WebViewClient to WebView.

 

       myweb.setWebViewClient(new mWebview());

This class will overridefollowing method.
onPageStarted()

this method is called when page is loading

onPageFinished()
this method is called when page is loaded completely.

shouldOverrideUrlLoading()

this method is called when user click on any link in web page.

19. define class.

  private class mWebview extends WebViewClient {
       
}

20. To overried methods use shortcut as Ctrl+O on Windows.

       @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
         super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {        
            super.onPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
             super.shouldOverrideUrlLoading(view, url);
        }

21. onPageStarted method we will set visibility of progressbar to Visibile

use setVisibility method.

 loading.setVisibility(View.VISIBLE);

22. same onPageFinished we will set visibility of progressbar to Gone.

loading.setVisibility(View.GONE);

23. now on shouldOverrideUrlLoading we will check url

if its start with http:// or https://

return false.

this will load within webview.

if its other links View Intent will called.

e.g. share button for whatsapp/

   if (url.startsWith("http://") || url.startsWith("https://")) {
                return false;
            } else {
      view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }

24. At last we also need to handle the back button. so previous page will load.

override method onBackPressed after mWebview class end.

25. Here we checked webview can go to previous page or not.

if can not go back means webiew on first page loaded then

super.onBackPressed() handled from AppCompact Activity class.

  @Override
    public void onBackPressed() {
        if (myweb.canGoBack()) {
            myweb.goBack();
        } else {
            super.onBackPressed();
        }
    }

26. Done.

now compile code and run app.

 

WebView in Android
WebView in Android

27. now our site androidcodr.com is opening…

we can see progressbar while loading.

WebView in Android
WebView in Android

you can click on links new page is loaded.

WebView in Android
WebView in Android

we can also go back to previous page.

Other Links also handled.

28. Here is full code of activity_main.xml

<?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.androidcodr.webview.MainActivity">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/webview" >

    </WebView>

    <ProgressBar
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="171dp"
        android:layout_y="239dp"
        android:id="@+id/progressBar"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="gone" />
</RelativeLayout>

29. Here is full code of MainActivity.java

package com.androidcodr.webview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    private WebView myweb;
    private ProgressBar loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myweb = (WebView) findViewById(R.id.webview);
        loading = (ProgressBar) findViewById(R.id.progressBar);


        myweb.setWebViewClient(new mWebview());
        myweb.getSettings().setJavaScriptEnabled(true);
        myweb.loadUrl("http://www.androidcodr.com");
    }

    private class mWebview extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loading.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            loading.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http://") || url.startsWith("https://")) {
                return false;
            } else {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        }
    }


    @Override
    public void onBackPressed() {
        if (myweb.canGoBack()) {
            myweb.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

Thanks.

If you Like post share with your Friends.

Subscribe us for new updates posts.

Follow us on Facebook Twitter and Google+


Share this

Leave a Reply

Your email address will not be published. Required fields are marked *