有什么方法可以强制主机立即创建它们,以便我可以通过 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)
public TabHost.TabSpec setContent(意图意图)
公共 TabHost.TabSpec setContent (TabHost.TabContentFactory contentFactory)