Create a singleton named NavigationHandler and add the below functions to it:
Function to open MainFragment:
public void openMainFragment(FragmentManager fragmentManager, MainFragment fragment){
String backStackName = fragment.getClass().getSimpleName();
fragmentManager.beginTransaction()
.replace(R.id.fl_main_container, fragment)
.addToBackStack(backStackName)
.commit();
}
Function to open SubFragment:
public void openSubFragment(FragmentManager fragmentManager, SubFragment fragment){
String backStackName = fragment.getClass().getSimpleName();
fragmentManager.popBackStackImmediate(backStackName, POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction()
.replace(R.id.fl_main_container, fragment)
.addToBackStack(backStackName)
.commit();
}
For backpress:
public void navigateBackBy(AppCompatActivity activity, int numOfFragments){
if(mFragmentManager.getBackStackEntryCount()==1){
activity.finish();
}
else {
int i;
for (i = 0; i < numOfFragments; i++) {
mFragmentManager.popBackStackImmediate();
}
}
}
In your Activity:
-
Call openMainFragment(…) to open the MainFragment with the list.
-
While calling your adapter constructor pass FragmentManager as a parameter.
-
Override onBackPressed() & add call navigateBackBy(this, 1);. This method is useful to go back by any no. of fragments.
Inside your adapter:
- On click of an item call openSubFragment(…).
15
solved How to fix fragments backstack issues in android