Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a Fragment from the back stack

I have a 3 fragments in an activity when the a tablet is held in portrait. However I only have 2 of these fragments when in landscape. The problem I am having is when going from portrait to landscape the activity is creating the 3rd fragment. I receive and error as this fragment cannot be created.

I have worked out that this fragment is being created because it is in the back stack.

I have tried to remove the fragment in the onDestroy method by using

FragmentTransaction f = fragmentManager.beginTransaction(); f.remove(mf); f.commit(); 

However the I get an error saying that I cannot use this function after the onSaveInstanceState

What would be the correct way of taking this fragment out of the back stack?

Update

I should probably add that the fragment I am having problems with is a mapFragment from this libary

https://github.com/petedoyle/android-support-v4-googlemaps

The way I use it is like so

mf = MapFragment.newInstance(1, true);  ft = fragmentManager.beginTransaction(); ft.replace(R.id.mapContainer, mf); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack("map"); ft.commit(); 
like image 488
jiduvah Avatar asked Jan 27 '12 12:01

jiduvah


People also ask

How do you detach a fragment?

To detach an added Fragment from an Activity, you use: getFragmentManager(). beginTransaction(). detach(mFragment). commit().

What is fragment back stack?

If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped. The optional name provided in the addToBackStack() call gives you the ability to pop back to that specific transaction using popBackStack() .

How do I remove a fragment from a transaction?

To remove a fragment from the host, call remove() , passing in a fragment instance that was retrieved from the fragment manager through findFragmentById() or findFragmentByTag() . If the fragment's view was previously added to a container, the view is removed from the container at this point.


1 Answers

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentTransaction trans = manager.beginTransaction(); trans.remove(myFrag); trans.commit(); manager.popBackStack(); 
like image 96
user123321 Avatar answered Oct 13 '22 16:10

user123321