Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

Android - Set fragment id

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...