Priyanka G
Priyanka G

Reputation: 47

How to remove fragment from stack programmatically?

In my application, from MainActivity I go to Fragment1 and from Fragment1 I replace Fragment1 with Fragment2. Now I want to remove Fragment1 from stack. How I do this?

Upvotes: 0

Views: 935

Answers (1)

Kintan Patel
Kintan Patel

Reputation: 1268

When you are added the fragment,just add the TAG for that fragment. With the use of that TAG you can easily remove your old fragment. Eg.

FragmentManager  fm = getSupportFragmentManager();
fm.replace(R.id.container,new MyFragment(),"TAG_FRAGMENT1").commit(); 

To remove old fragment use below code,

Fragment oldFragment = fm.findFragmentByTag("TAG_FRAGMENT1");
fm.beginTransaction().remove(oldFragment).commit();

After removing old fragment you can able to add new fragment.

Upvotes: 1

Related Questions