Sid Sid - 1 year ago 80
Java Question

How to navigate to last popped up fragment from next fragment?

I have 3 fragments right now. One is main fragment second is profile fragment and third is profile edit fragment.

MainFragment is called like this:

fragmentManager = getSupportFragmentManager();
DashboardFragment fragment1 = new DashboardFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.frame, fragment1, "DASHBOARD_FRAGMENT").commitAllowingStateLoss();


Now from main fragment I am navigating to profile fragment like this.

fragmentManager = ((MainActivity)(mContext)).getSupportFragmentManager();
ProfileFragment fragment1 = new ProfileFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.frame, fragment1, "PROFILE_FRAGMENT").addToBackStack("B").commit();


Now from profile fragment I am navigating to profile edit fragment like this:

fragmentManager = getActivity().getSupportFragmentManager();
ProfileEditFragment fragment1 = new ProfileEditFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().add(R.id.frame, fragment1, "PROFILE_EDIT_FRAGMENT").addToBackStack("C").commit();


Now navigation is like from main fragment to profile fragment and from profile fragment to profile edit fragment.

Now when I press back from profile edit fragment it directly goes to main fragment which shows blank.I want to go to profile fragment on back pressed from profile edit fragment and then back to main fragment on back press of profile fragment.

For this I have onBackPressed method in main activity, but its not working well.

@Override
public void onBackPressed() {

// Do nothing if the back button is disabled.
if (!mBackPressCancelled) {


if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
}
else {
super.onBackPressed();

}
}
}


what is going wrong? Please help. Thank you..

Answer Source

You have to add DashboardFragment to back stack also.

fragmentManager.beginTransaction().replace(R.id.frame, fragment1, "DASHBOARD_FRAGMENT").addToBackStack("A").commitAllowingStateLoss();

Also, change the if condition in your onBackPressed(). So, it will keep at least one fragment in your back stack.

if (getFragmentManager().getBackStackEntryCount() > 1) {
        getFragmentManager().popBackStackImmediate();
} else {
    super.onBackPressed();
}

Also, remove all popBackStack() before replace(). This line is not needed when you need to keep fragment in back stack.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download