gpt4 book ai didi

android - FragmentTabHost - 选项卡在第一次查看之前不可寻址

转载 作者:可可西里 更新时间:2023-11-01 18:47:56 27 4
gpt4 key购买 nike

我正在使用带有多个选项卡的 FragmentTabHost(构造如图 here 所示)。但是,我无法使用 getFragmentByTag(在这种情况下返回 null)随机寻址我的选项卡,除非已通过至少单击该选项卡一次来激活所寻址的选项卡。

FragmentTabHost 似乎延迟了选项卡的创建,直到我们真正需要它们(也就是用户单击它并想要查看它)。
有没有办法强制主机立即创建它们,以便我可以通过 getFragmentByTag 安全地访问它们?
或者是否可以“自行”创建选项卡并将它们添加到 TabHost?

最佳答案

Is there any way to force the Host to create them immediately such that I can safely access them by getFragmentByTag?

没有。因为事务是在 onAttachedToWindow() 处执行的。让我们看看 source code :

@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 处执行。

Or is it possible to create the Tabs "on my own" and just add them to the TabHost?

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

public TabHost.TabSpec setContent (int viewId)

public TabHost.TabSpec setContent (Intent intent)

public TabHost.TabSpec setContent (TabHost.TabContentFactory contentFactory)

关于android - FragmentTabHost - 选项卡在第一次查看之前不可寻址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18169806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com