【发布时间】:2026-02-25 02:05:02
【问题描述】:
嗯,我有一个简单的<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();
在我的代码中的其他地方,我想从 ID R.id.FragmentContainer 中获取 FragClass (extends Fragment) 对象。
我试过了
((ViewGroup) findViewById(R.id.FragmentContainer)).getChildAt(0)
或
((FrameLayout) findViewById(R.id.FragmentContainer)).getChildAt(0)
但他们返回的是View,而不是附加的Fragment。
我知道我可以将变量 aFrag 保存在某个地方,所以我不需要再次找到它。但我相信应该有办法找回它。
【问题讨论】:
-
感谢@Luksprog 的回复。但我无法向 aFrag 添加 ID。
-
没有,即使你用上面的方法和
R.id.FragmentContainer? -
哦,是的!答对了!我一直在问愚蠢的问题(嘘......)答案是:
((aFrag) getSupportFragmentManager().findFragmentById(R.id.FragmentContainer))。谢谢@Luksprog
标签: android android-layout android-fragments android-framelayout