Android FragmentTab主机和Fragments中的片段 [英] Android FragmentTab host and Fragments inside Fragments
问题描述
我有一个具有这样的层次结构的应用程序:
I have an app with hierarchy like this:
FragmentTabHost (Main Activity)
- Fragment (tab 1 content - splitter view)
- Fragment (lhs, list)
- Framment (rhs, content view)
- Fragment (tab 2 content)
- Fragment (tab 2 content)
所有片段视图都被资源夸大了。
All fragment views are being inflated from resources.
应用启动时,所有内容都会出现并且看起来不错。当我从第一个选项卡切换到另一个选项卡并再次返回时,出现膨胀异常,试图重新创建选项卡1的视图。
When the app starts everything appears and looks fine. When I switch from the first tab to another tab and back again I get inflate exceptions trying to recreate tab 1's views.
深入挖掘,这就是发生的情况:
Digging a little deeper, this is what's happening:
- 在第一次加载时,使splitter视图膨胀会导致其两个子片段被添加到片段管理器中。
- 从第一个选项卡切换到视图时,视图被销毁,但其子片段留在片段管理器中
- 在切换回第一个选项卡时,视图重新膨胀,并且由于旧的子片段仍在片段管理器中,因此在实例化新的子片段时(通过充气)会引发异常。
我已经通过从片段管理器中删除子片段(我正在使用Mono)来解决此问题,现在我可以无例外地切换制表符了。
I've worked around this by removing the child fragments from the fragment manager (I'm using Mono) and now I can switch tabs without the exception.
public override void OnDestroyView()
{
var ft = FragmentManager.BeginTransaction();
ft.Remove(FragmentManager.FindFragmentById(Resource.Id.ListFragment));
ft.Remove(FragmentManager.FindFragmentById(Resource.Id.ContentFragment));
ft.Commit();
base.OnDestroyView();
}
所以我有几个问题:
- 以上方法是否正确?
- 如果不是,我应该怎么做?
- 无论哪种方式,保存实例状态如何与所有这些相关联,以便在切换选项卡时不会丢失视图状态?
推荐答案
我不确定如何在Mono中执行此操作,但是要将子片段添加到另一个片段中,不能使用 FragmentManager
活动
中的code>。相反,您必须使用托管 Fragment
的 ChildFragmentManager
:
I'm not sure how to do this in Mono, but to add child fragments to another fragment, you can't use the FragmentManager
of the Activity
. Instead, you have to use the ChildFragmentManager
of the hosting Fragment
:
http://developer.android.com/reference /android/app/Fragment.html#getChildFragmentManager()
http://developer.android.com/reference/android/support/v4/app/Fragment.html#getChildFragmentManager()
活动
的主 FragmentManager
处理您的标签。
< tab1
的code> ChildFragmentManager 处理拆分视图。
The main FragmentManager
of the Activity
handles your tabs.
The ChildFragmentManager
of tab1
handles the split views.
这篇关于Android FragmentTab主机和Fragments中的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!