androidandroid-intentandroid-fragmentsandroid-webviewandroid-websettings

ImageButton in ActionBar for GoBack in WebView


I'm using Fragments and one of my Fragment I have a webview. I want to add a image button that will let user to go back.

I have 4 Fragments and their names are Fragment1,Fragment2,Fragment3,Fragment4.

Also I have 4 layouts tab1.xml tab2.xml tab3.xml tab4.xml and there is 4 webview objects in all layouts.

When I click Fragment1, it opens tab1.xml and tab1.xml's webview1 opens www.site.com and user starts surfing inside webview1.

If user visits 2 or more pages in webview1 I want this user let can go back with a button.

How can I do this?


Solution

  • In your decalarations:

    WebView web = null;
    

    In your onCreateView;

    // Prepare WebView.
    web = (WebView) v.findViewById(R.id.htmlDisplay);
    // Set WebView.
    final WebSettings webSettings = web.getSettings();
    
    // Enable JavaScript.
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    

    In your back button (not the physical one):

    web.goBack()
    

    If you want to use your physical back button:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_BACK:
                if(web.canGoBack() == true)
                {
                    web.goBack();
                }
                else
                {
                    finish();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }