Android-Set 片段 id

我如何设置一个 FragmentId,以便我可以使用 getSupportFragmentManager().findFragmentById(R.id.--)

116784 次浏览

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.

正如 Aleksey 指出的,您可以向 FragmentTransactionadd(int, Fragment)方法传递一个 ID。但是,这不指定片段的 ID。指定了要将 Fragment插入的 ViewGroup的 ID。这对于我所期望的目的来说并不是那么有用,因为它并不唯一地标识 Fragment,而是 ViewGroup。这些 ID 是 add(int, Fragment)0,可以动态地添加一个 add(int, Fragment)1片段。使用这样的方法来识别 Fragment将需要您为每个插入的 Fragment动态地添加 ViewGroup到布局中。那就太麻烦了。

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.

标记方法的另一个优点是,它可以识别没有添加到 UI 中的片段。请参见 FragmentTransaction 的 Add (片段,字符串)方法。Fragment不需要有 View!它们还可以用于在配置更改之间保持短暂状态!

在大多数情况下,可以使用片段标记和 ID。
可以在 FragmentTransaction.add(Fragment fragment, String tag );中设置标记值。 然后您可以使用命令 FragmentManager.findFragmentByTag(String tab)来查找有问题的片段。

正如 Tom 和其他人已经提到的,有一些方法可以将标记放在片段上并使用该标记进行识别。我在这些解决方案中遇到的一个后续问题是,片段在与 Activity (或者实际上是 FragmentManager)关联之前不会获得标记。如果需要在标记之前识别一个片段,该怎么办?

到目前为止,我的解决方案都依赖于世界上最古老的(Java)技巧: 创建一个最小化的模板片段,它在其中一个构造函数中接受一个 id,并提供一个返回该 id 的 getFragmentId()方法。然后,我让那些需要早期识别的片段扩展这个模板,瞧!问题解决了。

不幸的是,这个解决方案可能需要一组模板片段,每个片段类型一个,ListFragmentDialogFragment或者普通的旧 Fragment(POFO? !)需要早期鉴定。但是,考虑到所提供的收益,我认为对于碎片来说,这是可以控制的。

抱歉撕裂了你的伤口: -)

干杯!

你可能不需要知道碎片的身份。

来自文件:

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.

重要的部分是“在事务中添加时作为容器 ID”。

所以:

getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, new AwesomeFragment())
.commit();

然后

AwesomeFragment awesome = (AwesomeFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_holder);

将得到 R.id.part _ holder 中保存的任何(令人敬畏的)片段。

In addition to Tom's answer, replace method also supports the fragment tag, in addition to add method.

Use the following:

To add a fragment:

getFragmentManager().beginTransaction().add(R.id.fragment_container, fragmentToBeAdded, tag).commit();

确定现有的碎片:

getFragmentManager().findFragmentByTag(fragmentName);

When using a tag please do make sure to add the

fragmentTransaction.addToBackStack(null);

方法,以便恢复片段,而不是像开发人员指南中提到的那样销毁片段。

如果在执行删除某个片段的事务时没有调用 addToBackStack () ,那么在提交该事务时该片段将被销毁,用户无法导航回该片段。然而,如果在删除一个片段时调用 addToBackStack () ,那么该片段将被停止,如果用户返回导航,则稍后将恢复该片段。

你可以在 本页的末尾找到这个。

我浪费了大约30分钟试图找出为什么我的碎片没有被发现通过一个简单的 findFragmentByTag();电话