Android ChildFragmentManager().findFragmentById() always nul



>我偶然发现了一个疯狂的小"错误",或者我只是做错了什么。我正在尝试获取对片段内片段的引用。所以我们有ParentFragment,那是MainActivity的孩子。我可以毫无问题地获得对此 ParentFragment 的引用,因为ParentFragment是通过代码添加到MainActivity中的:

ParentFragment fragment = new ParentFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentPlaceholder, fragment);
transaction.commit();

我通过XML向ParentFragment中添加了一个ChildFragment,如下所示:

parent_fragment.xml

<RelativeLayout ... etc>
    .. some other views, findViewById('') works great on these.
    <fragment
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/childFragment1"
        android:tag="1"
        class="com.my.package.ChildFragment"
        android:name="com.my.package.ChildFragment"
        tools:layout="@layout/child_fragment" />
</RelativeLayout>

一切正常,子片段显示在父片段中。唯一的问题是;我找不到片段ById。

我已经尝试了多种方法来实现这一目标,应该如何完成(?

getChildFragmentManager().findFragmentById(R.id.childFragment1)

没用。此外,获取活动并使用该片段管理器不起作用(当然)。

我还尝试在ChildFragmentManager中获取所有片段,迭代它们等。但这总是返回 null:

getChildFragmentManager().getFragments()

你知道为什么会这样吗?如果不通过代码添加片段,我不能使用 ChildFragrentManager 吗?

谢谢!

您必须动态添加子片段。看这里:

注: 当布局出现时,您无法将布局膨胀为片段 包括一个<片段>。嵌套片段仅在添加时受支持 动态到片段。

如果您打算使用嵌套片段,请为各种奇怪的行为做好准备,您可以在Android平台的错误报告中找到它们:

https://code.google.com/p/android/issues/list?can=2&q=nested+fragment&sort=-opened&colspec=ID+Status+Priority+Owner+Summary+Stars+Reporter+Opened&cells=tiles

如果你想使用嵌套的片段,并且能够通过findFragmentById获取对它们的引用,你就不能使用支持包。

我将所有getSupportFragmentManager()更改为getFragmentManager(),并将所有FragmentActivity替换为常规Activity

现在它按预期工作,只需调用getChildFragmentManager().findFragmentById().

最新更新