Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove old Fragment from fragment manager

I'm trying to learn how to use Fragments in android. I'm trying to remove old fragment when new fragment is calling in android.

like image 279
khouloud mejdoub Avatar asked Mar 18 '14 09:03

khouloud mejdoub


People also ask

How do I detach a fragment?

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

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.


2 Answers

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT); if(fragment != null)     getSupportFragmentManager().beginTransaction().remove(fragment).commit(); 

That is it.

like image 139
Yashdeep Patel Avatar answered Sep 24 '22 12:09

Yashdeep Patel


If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.

// Create new fragment and transaction Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction();  // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null);  // Commit the transaction transaction.commit(); 

Refer this post: Replacing a fragment with another fragment inside activity group

Refer1: Replace a fragment programmatically

like image 27
Lokesh Avatar answered Sep 25 '22 12:09

Lokesh