3

I want to have a Fragment which provides the ability to create someting. After that i want to show the new "someting" in another fragment. After pressing the back button on the device i want to go back to the MainFragment and not to the CreateFragment (this works well). But after that the ShowFragment is still visible.

Here is my code:

In my MainActivity i got a MainFragment which has a button "Create".

After tap the button i load a "Create" Fragment.

fragmentManager.beginTransaction()
           .replace(R.id.container, CreateFragment.newInstance())
           .addToBackStack("Create")
           .commit();

If the user has entered some details he taps the "Ok" Button. This fires the following on the MainActivity.

fragmentManager.beginTransaction()
            .replace(R.id.container, ShowFragment.newInstance(id))
            .commit();

So far so good, but here comes the problem.

If the user taps the back button on the device he gets back to the MainFragment BUT the ShowFragment is still visible (under the MainFragment).

Update

This is what happens:

MainFragment > CreateFragment > ShowFragment > (BACK Button) > MainFragment (ShowFragment in the back)

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202

2 Answers2

1

Just pop the ShowFragment from the stack on the onBackPress Event as below:

@Override
public void onBackPressed() {
    final Fragment fragment = fragmentManager.findFragmentById(R.id.container);
    if (fragment != null) {
        fragmentManager.popBackStack();
    } else {
        super.onBackPressed();
    }
}
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
-2

Press the back button of fragment ShowFragment within your ShowFragment fragment will call the onBackPressed() method. Then when you call method popBackStack(), it will return you back to the CreateFragment.

Sample code -

public void onBackPressed()
{
  FragmentManager fm = getActivity().getSupportFragmentManager();
  fm.popBackStack();
}

See the post how-to-back-to-previous-fragment-on-pressing-manually-back-button-of-indivisual-fragment for more info with similar situation.

Community
  • 1
  • 1
sjain
  • 23,126
  • 28
  • 107
  • 185
  • Reason for downvote. What's wrong in the code if it can help. – sjain Apr 02 '14 at 09:17
  • 1) This code does pretty the same that the Activity onBackPressed() default implementation and requires Fragment modification and explicit calling. 2) The explanation is pretty unclear, it starts with "Press the back button of fragment " but the Fragment itself does not have/handle the back button. – Yaroslav Mytkalyk Apr 02 '14 at 09:34
  • See the OP's update - `ShowFragment > (BACK Button)`. The fragment clearly has the back button. The explicit calling is how you can do to go back of stack once you commit in a transaction. – sjain Apr 02 '14 at 10:45
  • I'm sure the OP means "ShowFragment is shown and then the back button of the Activity is pressed". – Yaroslav Mytkalyk Apr 02 '14 at 11:02