简体   繁体   中英

How to make WebView inside fragment to go back to previous tab?

I have a fragment which contains a webview.And the fragment is reused in all the four pages of a viewPager.What i want is, when the user clicks the back button i want the webView Fragment to go back to the previous tab of the current webViewFragment.And finally exit the activity.I can easily do this if the webView was inside an activity like this:

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

    }

But i cannot do this in a fragment because the fragment cannot override onBackPressed().How can i do this inside a fragment which is inside a viewPager

You can implement setOnKeyListener on webview to handle back button.

mWebview.setOnKeyListener(new View.OnKeyListener(){

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == MotionEvent.ACTION_UP
                        && mWebview.canGoBack())
                {
                    mWebview.goBack();
                    return true;
                }
                return false;
            }

        });

If there is no previous page in your webview then it will trigger usual onBackPressed .

Hope it helps you.

This code is perfect for fragment webview backpress.

You can implement setOnKeyListener on webview to handle back button

mWebview.setOnKeyListener(new View.OnKeyListener(){

    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == MotionEvent.ACTION_UP
                && mWebview.canGoBack())
        {
            mWebview.goBack();
            return true;
        }
        return false;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM