gpt4 book ai didi

android - 获取 fragment 动态附加到

转载 作者:IT王子 更新时间:2023-10-29 00:08:35 25 4
gpt4 key购买 nike

嗯,我有一个简单的 <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" />

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

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某处,所以我不需要再次找到它。但我相信应该有办法找回它。

最佳答案

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

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

引用:http://developer.android.com/guide/components/fragments.html#Adding

Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:

  • Supply the android:id attribute with a unique ID.
  • Supply the android:tag attribute with a unique string.
  • If you provide neither of the previous two, the system uses the ID of the container view.

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

所以这个问题的答案是:

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

感谢@Luksprog。

关于android - 获取 fragment 动态附加到 <FrameLayout>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15492717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com