Saturday, January 23, 2016

android - How to navigate WebView back forward history

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/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#fcfdfb"
    >
    <Button
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        android:enabled="false"
        />
    <Button
        android:id="@+id/btn_forward"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Forward"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:enabled="false"
        />
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/btn_back"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private WebView mWebView;
    private Button mButtonBack;
    private Button mButtonForward;

    private String mUrl="http://developer.android.com/guide/index.html";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        // Get the activity
        mActivity = MainActivity.this;

        // Change the action bar color
        getSupportActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#FFF91EC6"))
        );

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mWebView = (WebView) findViewById(R.id.web_view);
        mButtonBack = (Button) findViewById(R.id.btn_back);
        mButtonForward = (Button) findViewById(R.id.btn_forward);

        // Request to render the web page
        renderWebPage(mUrl);

        // Set a click listener for back button
        mButtonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    public boolean canGoBack ()
                        Gets whether this WebView has a back history item.

                    Returns
                        true : iff this WebView has a back history item
                */
                if (mWebView.canGoBack()) {
                    /*
                        public void goBack ()
                            Goes back in the history of this WebView.
                    */
                    mWebView.goBack();

                    // Display the notification
                    Toast.makeText(mContext,"Go To Back",Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Set a click listener for forward button
        mButtonForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    public boolean canGoForward ()
                        Gets whether this WebView has a forward history item.

                    Returns
                        true : iff this WebView has a forward history item
                */
                if (mWebView.canGoForward()) {
                    /*
                        public void goForward ()
                            Goes forward in the history of this WebView.
                    */
                    mWebView.goForward();

                    // Display the notification
                    Toast.makeText(mContext,"Go To Forward",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // Custom method to render a web page
    protected void renderWebPage(String urlToRender) {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // Do something on page loading started
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // Do something when page loading finished

                // Check web view back history availability
                if(mWebView.canGoBack()){
                    mButtonBack.setEnabled(true);
                }else {
                    mButtonBack.setEnabled(false);
                }

                // Check web view forward history availability
                if(mWebView.canGoForward()){
                    mButtonForward.setEnabled(true);
                }else {
                    mButtonForward.setEnabled(false);
                }
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int newProgress) {
            }
        });

        // Enable the javascript
        mWebView.getSettings().setJavaScriptEnabled(true);

        // Render the web page
        mWebView.loadUrl(urlToRender);
    }


    /*
        public void onBackPressed ()
            Called when the activity has detected the user's press of the back key. The default
            implementation simply finishes the current activity, but you can override this to
            do whatever you want.
    */
    @Override
    public void onBackPressed(){
        Toast.makeText(mContext,"Back Key Pressed",Toast.LENGTH_SHORT).show();
        // We also allow to navigate back history by pressing device back key
        if(mWebView.canGoBack()){
            Toast.makeText(mContext,"Back History Available",Toast.LENGTH_SHORT).show();
            mWebView.goBack();
        }else {
            Toast.makeText(mContext,"No Back History Found",Toast.LENGTH_SHORT).show();
            super.onBackPressed();
        }
    }
}