Abdul Waheed
Abdul Waheed

Reputation: 4678

Strange beviour of replacing fragment in android

I am not able to understand this behavior of Fragment replacing. In my application, I am moving from FragmentA to FragmentB then FragmentC and then FragmentX and from FragmentX I am moving FragmentD and I am not keeping FragmentX in backstack but when I am popping fragments FragmentX is also called as other fragments are called (for testing purpose I have set log in every fragment’s onCreate() method). I have read when one pops out fragment onCreate() of that fragment is called. I am using below code for replacing fragments.

public void replaceFragment(BaseFragment fragment,boolean isToAddBackStack){
baseFragment = fragment;
FragmentTransaction fragmentTransaction = fm.beginTransaction();

fragmentTransaction.replace(R.id.fragment_controller, fragment,        fragment.getName());
if(isToAddBackStack)
    fragmentTransaction.addToBackStack(fragment.getName());
else
    fragmentTransaction.addToBackStack(null);

fragmentTransaction.commit();
}

And I am using below code for pooping fragments because I don’t want user to navigate back that's why I am pooping I did not find fragmentX in the list of FragmentManager but still FragmentX is pooped out.Below is the code I am using for pooping out the fragments

public void clearBackStack(){
    for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
       fm.popBackStack();
    }
}

My questions are why FragmentX is being called while popping out fragments when I am not keeping that in backstack ,is there any other way of popping out fragment (When I say popping out I mean clearing back stack).

Note: When I clear back stack as I mentioned I am not keeping FragmentX in back stack FragmentX's onCreate() is called and then my UI gets hanged. I am not able to find the reason. Any help?

Upvotes: 0

Views: 138

Answers (1)

Rohan
Rohan

Reputation: 1190

Your problem lies in this part of your code -

if(isToAddBackStack)
    fragmentTransaction.addToBackStack(fragment.getName());
else
    fragmentTransaction.addToBackStack(null);

Calling fragmentTransaction.addToBackStack(null) does not mean that the transaction will not be added to the back stack. It means that the transaction will be added, but without a name.

Remove the else statement from your code, and it should work.

...
if(isToAddBackStack)
    fragmentTransaction.addToBackStack(fragment.getName());
// no else here
...

Upvotes: 1

Related Questions