【发布时间】:2016-01-28 11:09:15
【问题描述】:
我偶然发现了一个疯狂的小“错误”,或者我只是做错了什么。我正在尝试获取对片段内的片段的引用。所以我们有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>
一切正常,ChildFragment(s) 显示在 ParentFragment 中。唯一的事情是;我找不到 fragmentById。
我已经尝试了多种方法来实现这一点,应该怎么做(?):
getChildFragmentManager().findFragmentById(R.id.childFragment1)
没用。此外,获取 Activity 并使用该片段管理器不起作用(.. 当然)。
我也尝试在 ChildFragmentManager 中获取所有片段,对其进行迭代等。但这总是返回 null:
getChildFragmentManager().getFragments()
你知道为什么会这样吗?如果片段不是通过代码添加的,我不能使用 ChildFragrentManager 吗?
谢谢!
【问题讨论】:
-
我认为您应该尝试使用他们的
Tag来查找他们。 -
测试过了,没啥区别,注意
getChildFragmentManager().getFragments()也返回null。 -
哦。我之前没有真正使用过子片段,但是没有像
getSupportChildFragmentManager()这样的方法吗?考虑到这些似乎是支持片段,如果存在,那就是它。 -
不只是 getChildFragmentManager.. 让我试着让一切都成为常规片段而不是支持片段
-
支持片段的getChildFragmentManager方法返回支持片段管理器。支持 Fragment 自然不支持原生子 Fragment。
标签: android android-fragments child-fragment