0

I have set up a webview in one of the fragments of my application. The issue with backpress is that, if I have browsed through 5 pages in my webview, pressing back button will throw me all the way back to the first step (the hard coded URL). What I need to do is, pressing back while the user is on page5 gets the user on page 4, instead of all the way to page 1.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_blog, container, false);
    webView = (WebView) rootView.findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient());
            webView.loadUrl("http://www.facebook.com/");

            webView.setOnKeyListener(new View.OnKeyListener() {

                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {

                    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                        webView.goBack();
                        return true;
                    }
                   return false;
                }
            });
                return rootView;
            }
Rehan
  • 107
  • 1
  • 2
  • 7
  • Possible duplicate of [How to go back to previous page if back button is pressed in WebView?](http://stackoverflow.com/questions/6077141/how-to-go-back-to-previous-page-if-back-button-is-pressed-in-webview) – Miguel Garcia Dec 08 '15 at 13:45

1 Answers1

2

The problem is that the onKey method is called 2 times - for KeyEvent.ACTION_DOWN and KeyEvent.ACTION_UP.

So the solution is:

webView.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return false;
    }
});
Paul
  • 41
  • 1
  • 4