Mike Mike - 11 months ago 41
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


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

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() {
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_layout_container, new FragmentForgottenPassword(), "fragment_password")

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.

public void onBackPressed()
 if (getFragmentManager().getBackStackEntryCount() > 0) {
} else {

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