How to transition to the previous Fragment when pressing the back button?

Asked

Viewed 103 times

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 hit the physical button "back" from that last Fragment, the application closes, without giving any error message. I know it is possible to go back to the previous March simply by changing the function of the physical button "back", but faced with this problem I imagined that there could be another way to do this. From now on, thank you!

1 answer

0

Do so:

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 that Fragment to the stack, the tag I used "stack" can be anything. After that by clicking back it will go back to the previous Fragment and when it is in the last, it will close the app as it is now occurring

Browser other questions tagged

You are not signed in. Login or sign up in order to post.