SMGhost
SMGhost

Reputation: 4037

Android FragmentManager calls onCreateView while clearing fragments

I have these methods for fragment manipulation:

public void replaceFragment(Fragment fragment) {
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.main_frame, fragment);
    fragmentTransaction.commit();
    fragmentManager.executePendingTransactions();
}

public void addFragment(Fragment fragment, boolean addToBackStack) {
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.main_frame, fragment);
    if (addToBackStack) {
        fragmentTransaction.addToBackStack(fragment.getClass().getName());
    }
    fragmentTransaction.commit();
    fragmentManager.executePendingTransactions();
}

public void clearFragments() {
    if (fragmentManager.getBackStackEntryCount() > 0) {
        FragmentManager.BackStackEntry first = fragmentManager.getBackStackEntryAt(0);
        fragmentManager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
}

Scenario:

I start with fragment A, when activity is created. addFragment(new A, false);

Then I add fragment B. replaceFragment(new B);

I add another fragment C. addFragment(new C);

In C fragment I want to reset application to A fragment. I call clearFragments(); addFragment(new A, false);

The problem is that B fragment onCreateView is called after pressing button on C fragment that clears fragments and adds A fragment. I don't see the fragment, but it starts background thread that crashes my app. I need to clear all fragments without calling their onCreateView() methods.

Is this expected behaviour, or am I doing something wrong?

Upvotes: 1

Views: 1169

Answers (1)

Ayzen
Ayzen

Reputation: 983

Actually in such a scenario you will always return to the fragment B.

Step by step:

  1. Adding A.
  2. Replacing A with B <- after this step you don't have A within your activity.
  3. Adding C. Here you are adding another fragment and telling FragmentManager to preserve current state of fragments to the back stack. Your current state at this point is fragment B. Then fragment C is added.
  4. When you call clearFragments, FragmentManager returns to the first saved state - and this state is fragment B.

Maybe you forgot to mention something? I tried to put several entries in a back stack and then reset to the first state - onCreateView is called once, only for the first fragment.

Upvotes: 1

Related Questions