Back button in android webview within a fragment

余生颓废 提交于 2019-12-31 05:42:12

问题


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 press the back button and if i am already on home page the back button should kill the app.

I have tried using all the solution in the given link.

How to add "Go Back" function in WebView inside Fragment?

Please help.


回答1:


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());




回答2:


If you use the Web fragment and other fragments in your activity, this code works:

In your Activity:

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        // Webview back
        if (getSupportFragmentManager().findFragmentById(R.id.fragment_content) instanceof YourWebFragment){
            final YourWebFragment webFragment = (YourWebFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_content);
            if (webFragment != null){
                if (webFragment.onBackPressed()){
                    return;
                }
            }
        }
        // Fragments back
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }
}

In your Web Fragment:

public boolean onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
        return true;
    }
    return false;
}

Reference: https://stackoverflow.com/a/19268540/1329094 and https://stackoverflow.com/a/10631591/1329094



来源:https://stackoverflow.com/questions/42749269/back-button-in-android-webview-within-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!