我使用的是多选项卡的FragmentTabHost(构造如图所示这里)。但是,除非通过至少一次单击该选项卡激活了所寻址的选项卡,否则我无法使用getFragmentByTag(在这种情况下返回null)随机寻址选项卡。
FragmentTabHost似乎延迟了选项卡的创建,直到我们真正需要它们为止(aka用户单击它并想查看它)。
有什么方法可以强制主机立即创建它们,以便我可以通过getFragmentByTag安全地访问它们?
还是可以“自行创建”选项卡,然后将其添加到TabHost中?
有什么方法可以强制主机立即创建它们,以便我可以通过getFragmentByTag安全地访问它们?
否,因为交易是在处执行的onAttachedToWindow()
。让我们看一下源代码:
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
String currentTab = getCurrentTabTag();
// Go through all tabs and make sure their fragments match.
// the correct state.
FragmentTransaction ft = null;
for (int i=0; i<mTabs.size(); i++) {
TabInfo tab = mTabs.get(i);
tab.fragment = mFragmentManager.findFragmentByTag(tab.tag);
if (tab.fragment != null && !tab.fragment.isDetached()) {
if (tab.tag.equals(currentTab)) {
// The fragment for this tab is already there and
// active, and it is what we really want to have
// as the current tab. Nothing to do.
mLastTab = tab;
} else {
// This fragment was restored in the active state,
// but is not the current tab. Deactivate it.
if (ft == null) {
ft = mFragmentManager.beginTransaction();
}
ft.detach(tab.fragment);
}
}
}
// We are now ready to go. Make sure we are switched to the
// correct tab.
mAttached = true;
ft = doTabChanged(currentTab, ft);
if (ft != null) {
ft.commit();
mFragmentManager.executePendingTransactions();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAttached = false;
}
如您所见,在mFragmentManager.executePendingTransactions();
处执行onAttachedToWindow
。
还是可以“自行创建”选项卡,然后将其添加到TabHost中?
是的,您可以使用tabhost,也可以使用以下方法创建标签内容。
公共TabHost.TabSpec setContent(int viewId)
公共TabHost.TabSpec setContent(目的意图)
公共TabHost.TabSpec setContent(TabHost.TabContentFactory contentFactory)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句