Android - Set fragment id
How can I set a Fragment
's Id
so that I can use getSupportFragmentManager().findFragmentById(R.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 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!
Turns out you may not need to know the fragment id.
From the docs:
public abstract Fragment findFragmentById (int id)
Finds a fragment that was identified by the given id either
when inflated from XML or as the container ID when added in
a transaction.
The important part is "as the container ID when added in a transaction".
so:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, new AwesomeFragment())
.commit();
and then
AwesomeFragment awesome = (AwesomeFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_holder);
will get you whatever (awesome) fragment is held in R.id.fragment_holder.
In most cases you can use the fragment tag as well as the ID.
You can set the tag value in FragmentTransaction.add(Fragment fragment, String tag );
.
Then you can use the command FragmentManager.findFragmentByTag(String tab)
to find the fragment in question.