How to transition to the previous fragment when you press the back button?

2

I'm having the following problem: I have an activity, in which I call a fragment as follows:

    FragmentManager fm = getSupportFragmentManager();
    Fragment frag = new MyFragment();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.main_container, frag);
    ft.commit();

From this fragment that is called, there is a button that creates another fragment, which I did as follows:

    Fragment fragment = new MyOtherFragment();
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.main_container, fragment);
    ft.commit();

It turns out that when I press the "back" physical button from this last fragment, the application closes without giving any error message. I know it's possible to go back to the previous fragment simply by changing the function of the "back" physical button, but in the face of this problem I figured there might be another way to do this. Thanks in advance!

    
asked by anonymous 07.08.2018 / 22:54

1 answer

0

Do this:

Fragment fragment = new MyOtherFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_container, fragment);
ft.addToBackStack("pilha");
ft.commit();

The command ft.addToBackStack("pilha"); adds this fragment to the stack, the tag I used "stack" can be anything. After that click on the back it will return to the previous fragment and when it is in the last, it will close the app as it is happening now

    
08.08.2018 / 01:05