避免在FragmentTabHost标签交换数据重装 [英] Avoid reloading data in FragmentTabHost tab switching
问题描述
我已经卡式布局使用FragmentTabHost两个片段。在标签选择每个片段重新创建(onCreateView,onActivityCreated ......再次调用)。我载荷数据的第一片段(在onCreateView)移动到其他选项卡,当我回来的第一个片段,整个片段重建等数据再次加载。我不想对标签交换一次又一次加载数据。我该怎么办?
I have Tabbed layout with two fragments using FragmentTabHost. On tab selection each fragment is re-created (onCreateView, onActivityCreated... called again). I loads data in first fragment (in onCreateView) move to other tab and when I come back to first fragment, whole fragment is recreated and so data is again loaded. I don't want to load data again and again on tab switching. What should I do?
我试图安装和拆卸碎片,而不是添加/更换,但所有片段生命周期方法仍然被一再呼吁选项卡切换。什么是实现期望的行为的正确方法?
I tried attaching and detaching fragments instead of adding/replacing but all Fragment life cycle methods are still being called again and again on tab switching. What is the right way to achieve desired behavior?
推荐答案
您应该隐藏和显示你的片段。否则onCreateView如果添加/替换被调用。因此,如果碎片已经是present,使用显示和隐藏。
You should hide and show your fragments. Otherwise onCreateView gets called if you add/replace. So if the fragment is already present, use show and hide.
在您onTabChanged,请补充以下code。
In your onTabChanged, please add the below code.
if (mLastTab != newTab) {
FragmentTransaction ft = this.getSupportFragmentManager()
.beginTransaction();
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.hide(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(this,
newTab.clss.getName(), newTab.args);
ft.add(android.R.id.tabcontent, newTab.fragment, newTab.tag);
} else {
ft.show(newTab.fragment);
}
}
这篇关于避免在FragmentTabHost标签交换数据重装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!