Android - Set fragment id

android, android-fragments

Solution

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 `Fragment`s, but `ViewGroup`s. These IDs are of containers that one or more fragments can be added to dynamically. Using such a method to identify `Fragment`s would require you to add `ViewGroup`s 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. `Fragment`s need not have `View`s! They can also be used to persist ephemeral state between config changes!

Problem

How can I set a `Fragment`'s `Id` so that I can use `getSupportFragmentManager().findFragmentById(R.id.--)`?

Original source