Skip to content Skip to sidebar Skip to footer

Onbackpressed Not Following Backstack; Goes Directly To Home Fragment

I'm in a pickle and can't understand what's going on. I have my app using an OnBackPressed with a closing window and a home screen check, in short 'if home, else, use exit menu' @O

Solution 1:

If you're going to override onBackPressed, you have to handle the undoing of the backstrack yourself. This is what a FragmentActivity does:

/**
 * Take care of popping the fragment back stack or finishing the activity
 * as appropriate.
 */@OverridepublicvoidonBackPressed() {
    FragmentManagerfragmentManager= mFragments.getSupportFragmentManager();
    finalbooleanisStateSaved= fragmentManager.isStateSaved();
    if (isStateSaved && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
        // Older versions will throw an exception from the framework// FragmentManager.popBackStackImmediate(), so we'll just// return here. The Activity is likely already on its way out// since the fragmentManager has already been saved.return;
    }
    if (isStateSaved || !fragmentManager.popBackStackImmediate()) {
        super.onBackPressed();
    }
}

If you skip that, you don't get the fragment popping behavior. So just update your onBackPressed to include a pop of the fragment manager - if it succeeds, you can return early because the system did its thing popping the fragment as desired.

@OverridepublicvoidonBackPressed() {
    // Pressing back popped the back stack, nothing else to doFragmentManagerfragmentManager= getSupportFragmentManager();

    DrawerLayoutdrawer= (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } elseif (!fragmentManager.isStateSaved() && fragmentManager.popBackStackImmediate()) {
        return;
    } else {
        newAlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", newDialogInterface.OnClickListener() {
                    publicvoidonClick(DialogInterface dialog, int id) {
                        Home.this.finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }
}

UPDATE

You also need to update your displayView method, because right now it's always pushing something on the stack. So your "home" fragment will actually be the first thing on the stack and will pop leaving you with a blank screen. So if you're showing the "home" fragment, do not call addToBackStack on the fragment manager.

Further, you should not need to explicitly set the "home" fragment on pressing back as popping the backstack should do the right thing (see updated example above).

Hope that helps!

Post a Comment for "Onbackpressed Not Following Backstack; Goes Directly To Home Fragment"