0

I using BottomNavigationView with 3 main Fragment, like Fragment [A], [B], [C]. and Fragment [A] is default fragment, if Fragment [B] or [C] press back button must return to Fragment A. In fragment [B], I add button to get Another fragment just call it Fragment [D], but if in Fragment D i pressed back button app return into fragment [A].

So How to return into Fragment [B] when fragment [D] is press back button?

Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
rangga ario
  • 19
  • 1
  • 8
  • 3
    Possible duplicate of [How to pop back stack for Activity with multiple Fragments?](https://stackoverflow.com/questions/8772921/how-to-pop-back-stack-for-activity-with-multiple-fragments) – raj kavadia Nov 06 '19 at 06:43

2 Answers2

0

You can work with fragments stack. Implement onBackPressed() in activity.

@Override
public void onBackPressed() {
    //Work with fragments stack...

    int count = getSupportFragmentManager().getBackStackEntryCount();    
    if (count == 0) {
        super.onBackPressed();
    } else {
        getSupportFragmentManager().popBackStack();
    }

}
РСИТ _
  • 325
  • 1
  • 14
0

There is no onBackPressed function from Fragment.
That's why you should define callback interface for backPressed event.

    public interface IFragment {
        boolean onBackPressed();
    }

Then, you should implement your fragment [A], [B], [C], [D].

    @Override
    public boolean onBackPressed() {
        return true;
    }

And you should handle it in your host activity of Fragments.

    @Override
    public void onBackPressed() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();

        boolean handled = false;
        for(Fragment f : fragments) {
            if(f instanceof IFragment) {
                handled = ((IFragment) f).onBackPressed();
                if(handled) {
                    FragmentManager fm = getSupportFragmentManager();
                    for(String name : fragmentNames) {
                        fm.popBackStack(name, 0);
                    }
                    fm.beginTransaction().commit();
                }
            }
        }

        super.onBackPressed();
    }

I just implemented the code and let you know what you have to know.
Good luck.

libliboom
  • 532
  • 5
  • 17