0

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?

Ankita Shah
  • 1,866
  • 16
  • 31
Priyanka G
  • 47
  • 1
  • 2
  • 4
  • 1
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) { // handling fragment backbutton navigation getSupportFragmentManager().popBackStack(); } – Nithinlal Nov 24 '16 at 13:10
  • Possible duplicate of [Replacing a fragment with another fragment inside activity group](http://stackoverflow.com/questions/5658675/replacing-a-fragment-with-another-fragment-inside-activity-group) – denvercoder9 Nov 24 '16 at 13:13
  • If ur replacing Frament1 with fragment2 there is not change to backstack the fragment1. Replace Fragment = Add New fragment +Remove the old Fragment – Nithinlal Nov 24 '16 at 13:17
  • 1
    if you are replacing a fragment than fragment1 is removed by itself. but if you add fragment than it will add it to stack. – Aiyaz Parmar Nov 24 '16 at 13:17

1 Answers1

1

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.

Kintan Patel
  • 1,230
  • 8
  • 15