1

In order to navigate between fragments within 1 activity, I implemented a method called fragmentSwicher, that gets a fragment and replaces it with activated fragment in container.

So far so good, but now the problem is I want to re-use a fragment with different data, but my fragmentSwitcher method refuses to change fragment because of existing the fragment in backstack.

public void fragmentSwitcher(Fragment frg) {

    String backStateName = frg.getClass().getName();
    String fragmentTag = backStateName;

    FragmentManager manager = getFragmentManager();

    boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);

    FragmentTransaction ft = manager.beginTransaction();

    // check if fragment, is poped from backstack and there isnt any fragment in backstack like what we want to replace
    if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
        ft.replace(R.id.main_container, frg, fragmentTag);
    }

    // with this method, we make sure that, no loading fragment come into frament backstack list, so, we are back safe.
    if (!backStateName.equals("com.thetba.websitebuilder.fragments.ProgressFragments")) {
        ft.addToBackStack(backStateName);
    }

    ft.commit();

}

And this the method that handles backstack in MainActivity:

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() == 1) {
        finish();
    // check if there is more than one fragment in backstack, show it
    } else {
        getFragmentManager().popBackStack();
    }
}

I tried to partially solve this issue this way: I put

ft.replace(R.id.main_container, frg, fragmentTag);

outside of

    if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
        ft.replace(R.id.main_container, frg, fragmentTag);
    }

And fragmentSwitcher() replaces the same fragment with different data, BUT when user presses the back button, s/he will face with this fragment:

com.thetba.websitebuilder.fragments.ProgressFragments

that is not in backstack.

That said, what should I do to handle backstack when replacing same fragment?

Ali Abdolahi
  • 324
  • 3
  • 10

1 Answers1

0

This problem is because of replacing same Fragment class, although you can just repopulate Fragment with another data, but, handling BackStack in this solution is complicated.

so, for this purpose only you can introduce new Fragment with new name for replacement. to do this, you can add some random things at the end of backstackName string.

example:

if (backStateName.contains("com.thetba.websitebuilder.fragments.PagesFragment")) {
       backStateName += String.valueOf(getRandomInt(10, 500));
}
Ali Abdolahi
  • 324
  • 3
  • 10