Reputation: 5892
I have a problem with the backstack behaviour. That is what I am doing:
add(fragment1) + addToBackStack(null)
replace(fragment2) + addToBackStack(null)
What is happening:
Now I want to change my last backstacked fragment with a new transaction which put a new backstack fragment so:
[frag1, frag2] becomes [frag1, frag3]
but this transaction made by a popBackStack + replace
is making the frag1
to load by calling its onCreateView
and onActivityCreated
. I know this is the expected behaviour since this is how backstack works, but I am trying to find a way to avoid this preload.
Edit
In this question I am using the concept of backstack fragment for the transaction to be more clear. Every transaction here is an add+remove (which is a replace). The code for replace I am using is:
public int replaceFragment(BaseFragment newFragment, boolean addToBackStack, boolean animated, PopStackMode popMode) {
if (popMode != null) {
getSupportFragmentManager().popBackStack(newFragment.getFragmentTag(), popMode == PopStackMode.POP_INCLUSIVE ? FragmentManager
.POP_BACK_STACK_INCLUSIVE : 0);
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (animated) {
ft.setCustomAnimations(R.anim.slide_in_left, 0, R.anim.slide_out_right, 0);
}
ft.replace(R.id.fragment_container, newFragment, newFragment.getFragmentTag());
if (addToBackStack) {
ft.addToBackStack(newFragment.getFragmentTag());
}
return ft.commit();
}
You can see I am creating a navigation history based on the fragment backstack, as it was kind of a browser. When a "page" is added there is a fragment and a backstack transaction. In this context, I trying to:
I hope it is more clear.
Edit 2
I have filled a request feature for a flag that supports this behavior. Find it here.
Upvotes: 0
Views: 973
Reputation: 4123
First, you should understand that the backstack
doesn't save fragments, but it saves transactions
instead. When you call popBackStack
what it actually does is revert the previous transaction
. More on this here.
I think that you can do this:
addToBackStack
instead of null. i.e. addToBackStack("frag1")
.popBackStack + replace
, but instead just call replace
.onBackPressed
and if the current fragment being displayed is Frag3 (you can check this using findFragmentByTag
if you provided a tag in the replace
method) you can call getSupportFragmentManager().popBackStackImmediate("frag1", FragmentManager.POP_BACK_STACK_INCLUSIVE);
(otherwise call the super.onBackPressed
)Upvotes: 0