Android – Set fragment id

You can’t set a fragment’s ID programmatically.

There is however, a String tag that you can set inside the FragmentTransaction which can be used to uniquely identify a Fragment.

As Aleksey pointed out, you can pass an ID to FragmentTransaction‘s add(int, Fragment) method. However, this does not specify the ID for a Fragment. It specifies the ID of a ViewGroup to insert the Fragment into. This is not that useful for the purpose I expect you have, because it does not uniquely identify Fragments, but ViewGroups. These IDs are of containers that one or more fragments can be added to dynamically. Using such a method to identify Fragments would require you to add ViewGroups dynamically to the Layout for every Fragment you insert. That would be pretty cumbersome.

So if your question is how to create a unique identifier for a Fragment you’re adding dynamically, the answer is to use FragmentTransaction‘s add(int containerViewId, Fragment fragment, String tag) method and FragmentManager‘s findFragmentByTag(String) method.

In one of my apps, I was forced to generate strings dynamically. But it’s not that expensive relative to the actual FragmentTransaction, anyway.

Another advantage to the tag method is that it can identify a Fragment that isn’t being added to the UI. See FragmentTransaction’s add(Fragment, String) method. Fragments need not have Views! They can also be used to persist ephemeral state between config changes!

Leave a Comment