Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between accessing fragments by Tag or Id

I know I can create a fragment and add it via Tag or Id. Is it optional to use either one? Is there any kind of reason why I should use one over the other?

model = new ModelFragment();

//tag
getSupportFragmentManager().beginTransaction().add(model, "tag").commit();
//id
getSupportFragmentManager().beginTransaction().add( 4, model).commit();
like image 738
Juan Mendez Avatar asked Mar 21 '23 21:03

Juan Mendez


2 Answers

IDs are used for static fragments, fragments whose state you don't want to modify during the activity life cycle.

To dynamically add a fragment use tags :

android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, fragment, TAG);
    ft.commit();

To get the fragment somewhere in code, use something like:

if(getFragmentManager().findFragmentByTag(TAG)!=null){
      ft.remove(getFragmentManager().findFragmentByTag(TAG));
      ft.commit();  
 }
like image 65
geekoraul Avatar answered Apr 01 '23 21:04

geekoraul


I believe you can only add an id to a Fragment if it is a static Fragment (i.e. via xml). If you want to dynamically add Fragments via FragmentTransaction the third parameter of add() is a String for the tag. Giving a tag is optional, but recommended so you can get a hold of the Fragment later on.

On the id case you are showing, the first parameter of add() is the layout id of the container you want to add the Fragment to, not the id for the Fragment itself.

like image 32
Emmanuel Avatar answered Apr 01 '23 23:04

Emmanuel