9

Can any one help me. I have a Fragment say FRAGMENT A and am adding it to a layout dynamically...Suppose i have added 3 instance of FRAGMENT A to that layout.Then How i can Remove that 3 Fragment instance programmatically.I tried google searches and also another stackoverflow threads but they are not working..

PLease help me

Thank you

Sam
  • 4,046
  • 8
  • 31
  • 47

1 Answers1

27

it's actually pretty simple:

let's say you added the fragment like this:

fragmentTransac.add(R.id.content, fragA);

instead, you'll add it with a TAG too

fragmentTransac.add(R.id.content, new FragA(), "first");
// then the other
fragmentTransac.add(R.id.content, new FragA(), "second");

then to remove:

Fragment f = getFragmentManager().findFragmentByTag("first");
if(f!=null) fragmentTransac.remove(f);
fragmentTransac.commit();

happy coding =]

ibrabeicker
  • 1,786
  • 2
  • 19
  • 31
Budius
  • 39,391
  • 16
  • 102
  • 144
  • hi,thanks for your help...but its not working..can you suggest another way – Sam Apr 02 '13 at 10:45
  • that IS the way. If it's not working it's because it's not being correctly implemented. Did you understand that the object `fragmentTransac` I put in the example is the FragmentTransaction that is usually obtained from getFragmentManager().beginTransaction()? Also if you're using the compatibility pack instad of getFragmentmanager() you should call getSupportFragmentManager()? I didn't include those details because they are quite basic. – Budius Apr 02 '13 at 10:48
  • ye i knpw those things...i put like thisFragment f = getSupportFragmentManager().findFragmentByTag("hi"); FragmentTransaction ft=getSupportFragmentManager().beginTransaction(); ft.remove(f); – Sam Apr 02 '13 at 10:52
  • 4
    are you forgetting to commit() ? – Budius Apr 02 '13 at 11:10
  • Thankyou Very Much, It Saved My Time :) – Android Dev Jun 27 '16 at 06:38
  • You are amazing. So clear your solution so happy we are – hikmet_anil Dec 20 '18 at 18:21