40

好吧,我有一个简单的<FrameLayout>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/FragmentContainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

然后在我的代码中,我添加了一个片段:

FragClass aFrag = new FragClass();
getSupportFragmentManager().beginTransaction()
        .replace(R.id.FragmentContainer, aFrag).commit();

在我的代码中的其他地方,我想FragClass (extends Fragment)从 ID 中获取该对象R.id.FragmentContainer

我努力了

((ViewGroup) findViewById(R.id.FragmentContainer)).getChildAt(0)

或者

((FrameLayout) findViewById(R.id.FragmentContainer)).getChildAt(0)

但他们返回的是View, 而不是Fragment附加的。

我知道我可以将变量保存在aFrag某个地方,所以我不需要再次找到它。但我相信应该有办法找回它。

4

1 回答 1

94

让我用一个完整的答案来结束它:)

在这种情况下,动态添加Fragment的使用容器的 ID View( ViewGroup)。

参考:http: //developer.android.com/guide/components/fragments.html#Adding

注意:每个片段都需要一个唯一标识符,如果活动重新启动,系统可以使用该标识符来恢复片段(并且您可以使用它来捕获片段以执行事务,例如删除它)。可以通过三种方式为片段提供 ID:

  • 为 android:id 属性提供唯一 ID。
  • 为 android:tag 属性提供一个唯一的字符串。
  • 如果前两个都不提供,系统将使用容器视图的 ID。

这是因为它Fragment毕竟是。我们必须使用getSupportFragmentManager().findFragmentById()它来检索它,它返回 a Fragment,而不是findViewById()返回 a View

所以这个问题的答案是:

((aFrag) getSupportFragmentManager().findFragmentById(R.id.FragmentContainer))

感谢@Luksprog。

于 2013-03-20T11:38:39.017 回答