FragmentTabHost – 选项卡不可寻址,直到第一次查看

我使用带有多个选项卡的FragmentTabHost(如此处所示构build)。 然而,我不能随意解决我的标签与getFragmentByTag(在这种情况下返回null),除非通过点击标签至less一次激活寻址标签。

FragmentTabHost似乎推迟了标签的创build,直到我们确实需要它们(也就是用户点击它并想要查看它)。
有没有办法强制主机立即创build它们,以便我可以通过getFragmentByTag安全地访问它们?
或者是否有可能创build“我自己”的标签,只是将它们添加到TabHost?

Solutions Collecting From Web of "FragmentTabHost – 选项卡不可寻址,直到第一次查看"

有没有办法强制主机立即创build它们,以便我可以通过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被执行。

或者是否有可能创build“我自己”的标签,只是将它们添加到TabHost?

是的,你可以使用tabhost ,你可以用下面的方法创build标签内容。

public TabHost.TabSpec setContent(int viewId)

公共TabHost.TabSpec setContent(意图意图)

public TabHost.TabSpec setContent(TabHost.TabContentFactory contentFactory)