Android TabHost 默认选项卡 : First Added Tab Is Always Created

标签 android android-tabhost

考虑将初始/默认选项卡设置为第二个选项卡的场景:

TabHost _tabHost = getTabHost();
Intent intent0 = new Intent(this, Activity0.class);
Intent intent1 = new Intent(this, Activity1.class);
TabHost.TabSpec spec0 = _tabHost.newTabSpec("0").setIndicator(_vw0).setContent(intent0);
TabHost.TabSpec spec1 = _tabHost.newTabSpec("1").setIndicator(_vw1).setContent(intent1);
_tabHost.addTab(tabSpec0);
_tabHost.addTab(tabSpec1);

_tabHost.setCurrentTab(1);

所有在线资源都显示设置默认选项卡是通过调用 setCurrentTab(1) 完成的 - 然而上面的代码实际上会先调用 Activity0 的 onCreate,然后在 setCurrentTab(1) 行运行后调用 Activity1 的 onCreate。

在深入研究源代码后,我注意到 TabHost 的 addTab() 方法在第一次调用时自行调用了 setCurrentTab(0):

public void addTab(TabSpec tabSpec) {
        ...
        ...
        ...

        if (mCurrentTab == -1) {
            setCurrentTab(0);   <-- THIS will start first added Activity NO MATTER WHAT
        }
    }

如果您想默认使用第二个选项卡启动您的应用程序,这显然是一个问题。当我只需要 1 个 Activity 时,我不想加载 2 个 Activity 。

我正在考虑编写我自己的 addTab 方法,但实现依赖于许多私有(private)成员(大多数是 protected ,但少数是私有(private)的)。

我的 Activity0 在其 onCreate 上有一些繁重的逻辑,所以我不想不必要地运行它,而是默认在 Acivity1 上启动。

有什么想法吗?

最佳答案

我确实遇到了同样的问题,可能最有效的解决方案是 create an empty invisible/hidden first tab其 Activity 消耗的 CPU 少于您的真实 Activity 。

关于Android TabHost 默认选项卡 : First Added Tab Is Always Created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30748784/

相关文章:

android - ScrollView 中需要双击才能触发的最后一个元素

java - 如何从数据库表中删除特定项目?

java - 当另一个 fragment 的按钮尝试打开它时,时间选择器对话框会使应用程序崩溃

android - 如何像 "Home", "News & Weather app"那样用手指移动滑动标签内容(TabActivity)?

android - 未找到 TabHost addFlags()

android - 通过拖放重新排序 LazyColumn 项目

java - ListView不显示所有项目

android:layout_marginBottom 底部不留空间

android - 如何为选项卡 TabWidget 添加父对齐?

Android onActivityResult 从未调用过