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
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