1

I have one activity, and three fragments, this is the life cycle:

  1. Open app (Loads activity)
  2. Press button (Loads fragment A)
  3. Press another button (Loads fragment B)

Activity -> Fragment A -> Fragment B

What I want is that if I press the back button in Fragment B it shows me the Activity

How do I do it?

Right now, if I press the back button it shows me the Fragment A

Edit: This is the way I call Fragment B

 public void changeFragment(Fragment fragment, boolean addToBackStack) {

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.addToBackStack(null);
        ft.replace(R.id.content_frame, fragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.commit();
    }
Ophy
  • 81
  • 1
  • 12
  • Your addToBackStack boolean is not needed, as it is not being used. – miguelarc Jun 11 '18 at 18:52
  • I know that. But that is not the issue, even with this code, **Fragment A** still shows when I press the back button @miguelarc – Ophy Jun 11 '18 at 18:55
  • Is this function replacing the same id you are using for calling the fragment A in your activity? – miguelarc Jun 11 '18 at 18:58
  • You have more info [here](https://developer.android.com/training/basics/fragments/fragment-ui) about fragment transaction. Check under the fragment replace section – miguelarc Jun 11 '18 at 19:00
  • Yes, is replacing the same id. @miguelarc – Ophy Jun 11 '18 at 19:11
  • Try removing the setTransition method. According the android docs [here](https://developer.android.com/reference/android/support/v4/app/FragmentTransaction), FragmentTransaction.TRANSIT_FRAGMENT_OPEN adds the fragment onto de stack. – miguelarc Jun 11 '18 at 19:14
  • If you don't need the backstack, simply doesn't addToBackStack. – Marcos Vasconcelos Jun 11 '18 at 20:01

2 Answers2

2

You are adding the fragment B on top of fragment A, using add() in the FragmentTransaction. If you use replace() instead, the fragment A will be replaced with the fragment B, not adding it to the backstack, so that when you press back in your fragment B, the Activity is shown instead of fragment A. Check this for more details on how to replace a fragment.

miguelarc
  • 791
  • 7
  • 13
  • Could you please help me with another question? [link](https://stackoverflow.com/questions/50724518/resize-layout-dynamically-based-on-children) – Ophy Jun 11 '18 at 20:01
1

After some time, my solution was playing with the onBackPressed in the activity:

@Override
public void onBackPressed() {

    FragmentManager fm = this.getSupportFragmentManager();
    if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
    } else {
        super.onBackPressed();
    }


}
Ophy
  • 81
  • 1
  • 12