Mike Mike - 6 months ago 16
Java Question

Implementing back stacks with fragments

I'm attempting to implement a back stack while using fragments, but when using the Back button, I keep getting taken out of the app to the home screen.

Activity opens fragment A; Fragment A has a clickable TextView that opens fragment B (this works). Hitting BACK should return me to fragment A, but it takes me to the home screen instead.

Here is the activity's call to the opening of fragment A in

onCreate
:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_layout_container, new FragmentLogin(), "fragment_login")
.addToBackStack("login_screen")
.commit();

Log.d("Back", getFragmentManager().getBackStackEntryCount() +" <- Entry Count at LoginActivity.onCreate" );


At this point, the Log prints
0 <- Entry Count at LoginActivity.onCreate
. Something I've done wrong keeps this from printing 1.

Then, the Fragment A has this listener:

forgottenPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_layout_container, new FragmentForgottenPassword(), "fragment_password")
.addToBackStack("forgotten_password")
.commit();

Log.d("Back", getFragmentManager().getBackStackEntryCount() + " <- Entry Count at FragmentLogin.onCreateView.Listener");
}
});


The Log here prints
1 <- Entry Count at FragmentLogin.onCreateView.Listener
. Here, the listener works and opens fragment B - but the back button returns me to the home screen.

Answer
 @Override
public void onBackPressed()
{
 if (getFragmentManager().getBackStackEntryCount() > 0) {
    getFragmentManager().popBackStack();
} else {
    super.onBackPressed();
    }
}

Use this in your Activity it should pop out the fragments already added to backstack