Tuesday, January 26, 2016

android - Custom context menu for WebView

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"
    >
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
res/menu/webview_context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <item
        android:id="@+id/refresh"
        android:title="Refresh"
        app:showAsAction="always"
        />
    <item
        android:id="@+id/show_title"
        android:title="Show Page Title"
        app:showAsAction="always"
        />
    <item
        android:id="@+id/show_url"
        android:title="Show Page URL"
        app:showAsAction="always"
        />
</menu>
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.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
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 String mUrl="http://developer.android.com/guide/index.html";
    private String mTitle = "";


    @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("#FFFF0004"))
        );

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

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

        /*
            public void registerForContextMenu (View view)
                Registers a context menu to be shown for the given view (multiple views can show the
                context menu). This method will set the View.OnCreateContextMenuListener on the view
                to this activity, so onCreateContextMenu(ContextMenu, View, ContextMenuInfo) will be
                called when it is time to show the context menu.

            Parameters
                view : The view that should show a context menu.

        */
        // First step to show a custom context menu on web view
        registerForContextMenu(mWebView);

    }

    // 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
                mUrl = url;
                // Page title is not available in this stage
                mTitle = "";
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // Do something when page loading finished
                mUrl = url;
                // Page title is available in this stage
                mTitle = view.getTitle();
            }
        });

        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 onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
            Called when a context menu for the view is about to be shown.
            Unlike onCreateOptionsMenu(Menu), this will be called every time the context menu is
            about to be shown and should be populated for the view (or item inside the view for
            AdapterView subclasses, this can be found in the menuInfo)).

            Use onContextItemSelected(android.view.MenuItem) to know when an item has been selected.

            It is not safe to hold onto the context menu after this method returns.

        Parameters
            menu : The context menu that is being built
            v : The view for which the context menu is being built
            menuInfo : Extra information about the item for which the context menu should be shown.
                       This information will vary depending on the class of v.
    */
    @Override
    public void onCreateContextMenu(
            ContextMenu menu,
            View v,
            ContextMenu.ContextMenuInfo menuInfo
        ){
        super.onCreateContextMenu(menu, v, menuInfo);

        /*
            MenuInflater
                This class is used to instantiate menu XML files into Menu objects.

                For performance reasons, menu inflation relies heavily on pre-processing of XML
                files that is done at build time.
        */
        /*
            public MenuInflater getMenuInflater ()
                Returns a MenuInflater with this context.
        */
        MenuInflater inflater = getMenuInflater();

        /*
            public void inflate (int menuRes, Menu menu)
                Inflate a menu hierarchy from the specified XML resource. Throws InflateException if there is an error.

            Parameters
                menuRes : Resource ID for an XML layout resource to load (e.g., R.menu.main_activity)
                menu : The Menu to inflate into. The items and submenus will be added to this Menu.

        */
        inflater.inflate(R.menu.webview_context_menu, menu);
    }


    /*
        public boolean onContextItemSelected (MenuItem item)
            This hook is called whenever an item in a context menu is selected. The default
            implementation simply returns false to have the normal processing happen (calling the
            item's Runnable or sending a message to its Handler as appropriate). You can use this
            method for any items for which you would like to do processing without
            those other facilities.

            Use getMenuInfo() to get extra information set by the View that added this menu item.

            Derived classes should call through to the base class for it to perform the
            default menu handling.

        Parameters
            item : The context menu item that was selected.
        Returns
            boolean : Return false to allow normal context menu processing to proceed,
                      true to consume it here.
    */
    @Override
    public boolean onContextItemSelected(MenuItem item){
        // Handle the menu item selection
        switch(item.getItemId()){
            case R.id.refresh:
                // Render the page again
                renderWebPage(mUrl);
                Toast.makeText(mContext,"Page Reloaded",Toast.LENGTH_SHORT).show();
                return true;
            case R.id.show_title:
                Toast.makeText(mContext,mTitle,Toast.LENGTH_SHORT).show();
                return true;
            case R.id.show_url:
                Toast.makeText(mContext,mUrl,Toast.LENGTH_SHORT).show();
                return true;
            default:
                super.onContextItemSelected(item);
        }
        return false;
    }
}