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();
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With