I have fragments say CompanyFragment,DashboardFragment,CalendarFragment. My default fragment is CompanyFragment.
Expected Flow Should be
- Select Company from CompanyFragment
- Navigating to DashboardFragment
- Changing date from Dashboard so navigating to CalenderFragment
- After selecting date from CalenderFragment should come back to DashboardFragment
Now I have three fragments added on Fragment manager CompanyFragment -> DashboardFragment -> CalenderFragment
I am using following code snippet to add/replace fragment
public void setFragmentToContainer(Fragment fragment) {
final String tag = fragment.getClass().getName();
if (manager == null) {
manager = getSupportFragmentManager();
}
transaction = manager.beginTransaction();
if (isFragmentInBackstack(manager, tag)) {
if (fragment instanceof DayPartStoreListingFragment) {
} else {
manager.popBackStackImmediate(tag, manager.POP_BACK_STACK_INCLUSIVE);
}
} else {
// Fragment doesn't exist
}
if (fragment instanceof CalenderFragment) {
transaction.setCustomAnimations(R.anim.slide_up, 0, 0, R.anim.slide_down);
}
if (fragment instanceof DayPartStoreListingFragment) {
transaction.add(R.id.layout_content, fragment, tag);
} else {
transaction.replace(R.id.layout_content, fragment, tag);
}
if (fragment instanceof CompanyLevelFragment) {
//Exit app on back press
} else {
transaction.addToBackStack(tag);
}
transaction.commit();
}
To check fragment entries in fragmentmanager I am using following code
public static boolean isFragmentInBackstack(final FragmentManager fragmentManager, final String fragmentTagName) {
for (int entry = 0; entry < fragmentManager.getBackStackEntryCount(); entry++) {
if (fragmentTagName.equals(fragmentManager.getBackStackEntryAt(entry).getName())) {
return true;
}
}
return false;
}
Problem is: When I tried to open DashboardFragment from CalendarFragment then for the first time onResume of CompanyFragment gets called and then DashboardFragment onResume gets called. Note: I haven't called CompanyFragment from CalenderFragment,CompanyFragments onResume Automatically gets called before onResume of DashboardFragmet. The same case happening for another fragments also. After date change onResume of previous fragment gets called first and then onResume on requested fragment.
After debugging i found issue in manager.popBackStackImmediate(tag, manager.POP_BACK_STACK_INCLUSIVE);
if I remove this line from code then above scenario not getting reproduced. But I need this line to clear older entries of same fragment from backstack. I really need help.
Step 1 : Used Add method for Fragment transaction not used replace
Step 2:Write onBAckPressed on Main Activity of Fragment
May be this code will be work try it ...