将Fragment动态附加到<FrameLayout>?

mid*_*ite 38 android android-layout android-fragments android-framelayout

好吧,我有一个简单的<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" />
Run Code Online (Sandbox Code Playgroud)

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

FragClass aFrag = new FragClass();
getSupportFragmentManager().beginTransaction()
        .replace(R.id.FragmentContainer, aFrag).commit();
Run Code Online (Sandbox Code Playgroud)

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

我试过了

((ViewGroup) findViewById(R.id.FragmentContainer)).getChildAt(0)
Run Code Online (Sandbox Code Playgroud)

要么

((FrameLayout) findViewById(R.id.FragmentContainer)).getChildAt(0)
Run Code Online (Sandbox Code Playgroud)

但他们正在返回View,而不是Fragment依附于它.

我知道我可以将变量保留在aFrag某处,所以我不需要再找到它.但我相信应该有办法来解决它.

mid*_*ite 87

让我用完整的答案把它包起来:)

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

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

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

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

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

所以这个问题的答案是:

((aFrag) getSupportFragmentManager().findFragmentById(R.id.FragmentContainer))
Run Code Online (Sandbox Code Playgroud)

感谢@Luksprog.