Back button in android webview within a fragment

后端 未结 3 1020
傲寒
傲寒 2021-01-26 16:10

I have created a webview within a fragment however when I am trying to press the back button, it is killing the app instead of going back. What i want is to go back when i pres

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-26 16:46

    You can override the Activity's onBackPressed() method and check if there is any previous fragment in the backstack to pop back by calling getFragmentManager().popBackStackImmediate() or getSupportFragmentManager().popBackStackImmediate() like the code below:

    @Override
    public void onBackPressed() {
        if (!getFragmentManager().popBackStackImmediate()) {
            super.onBackPressed();        
        }
    }
    

    Don't forget to call .addToBackStack(null) before you call commit() to add the fragmenttransaction to the backstack.

    And if you want to press back button to go back to previous webpage user has navigated in the WebView before go back to previous fragment, you can do this:

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
                webView.goBack();
        } else if (!getFragmentManager().popBackStackImmediate()) {
            super.onBackPressed();        
        }
    }
    

    And remember to set your webView to load any webpage in the WebView by calling webView.setWebViewClient(new WebViewClient());

提交回复
热议问题