Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment still exists after remove?

Tags:

1 Add two fragments to FragmentManager

FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft1 = fm.beginTransaction(); ft1.add(containerId, fragment1, "fragment1"); ft1.addToBackStack(null); ft1.commitAllowingStateLoss();  FragmentTransaction ft2 = fm.beginTransaction(); ft2.add(containerId, fragment2, "fragment2"); ft2.addToBackStack(null); ft2.commitAllowingStateLoss(); 

2 Change mobile setting Developer Options-> Don't Keep Activities-> ON

3 Remove all fragments after activity was recreated

FragmentTransaction ft3 = fm.beginTransaction(); for(Fragment f : fm.getFragments())  ft3.remove(f);  ft3.commitAllowingStateLoss(); 

My question is why fm.findFragmentByTag("fragment1") is NOT null after remove?

minSdkVersion 17 targetSdkVersion 22 compileSdkVersion 22

like image 296
Jingqi Xu Avatar asked Jan 04 '16 06:01

Jingqi Xu


People also ask

What is backstack in Fragment?

Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.

What is FragmentManager in Android?

A FragmentManager manages Fragments in Android, specifically it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments.

What is a child Fragment?

Architectural structure of an Android single-activity screen This means that a single activity as a parent can have one or more fragments as children. Only the fragments are replaced within an event or navigation, so that the original parent activity continues to function as a container.


2 Answers

try this code for remove the fragment

FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentTransaction trans = manager.beginTransaction(); trans.remove(myFrag); trans.commit(); manager.popBackStack(); 

i think you have not add this method

manager.popBackStack(); 

or

getSupportFragmentManager().popBackStack() 
like image 171
Saif Avatar answered Sep 24 '22 18:09

Saif


use popBackStackImmediate() instead of popBackStack() which insure fragment is removed from backstack immediately. transection's remove method does not remove fragment from backstack it just for transection.

like image 35
CodingRat Avatar answered Sep 26 '22 18:09

CodingRat