Android fragments of navigation and backstack

I have a title bar (like a menu) and 4 fragments (MAIN, A, B, C), of which MAIN should be the "main / root" fragment for the backstack.

I have a problem when the user goes through the menu, for example, MAIN> A> B> C. If I just use backstack, it will go in the reverse order, which I do not want. I need a return button to return to MAIN no matter how the user navigated to one of these 3.

enter image description here

My current code (which is wrong, it closes the application if it is not in the MAIN, and the current fragment is switched from another non-MAIN fragment) looks like this:

private void SwitchFragment(Fragment pFragment) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.main_fl_fragmentcontainer, pFragment); if (_CurrentFragment == _Frag_Main) ft.addToBackStack(null); ft.commit(); _CurrentFragment = pFragment; } 
+8
android android-fragments navigation back-stack
source share
1 answer

Your stack should contain a maximum of 2 fragments

View is visible Main - onBackstack / AorBorC is visible. User clicked on the back. User clicks back button ==> end of application

I believe that A / B / C are displayed in the same view, so in this case

When the user clicks on your menu, you should check if A / B / C is currently displayed, and replace it with the one selected by the user.

 private void displayFragment(Fragment pFragment) { Fragment fr = getSupportFragmentManager() .findFragmentById(R.id.main_fl_fragmentcontainer); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.main_fl_fragmentcontainer, pFragment); if (_CurrentFragment == _Frag_Main) { ft.addToBackStack(null); } ft.commit(); _CurrentFragment = pFragment; } 

can override the OnBackPressed method of your activity.

+4
source share

All Articles