android - TabHost 动态添加标签页

标签 android android-layout android-studio

我有一个 TabHost,我想动态创建标签。我看过很多例子,但它们没有用。

TabHost tabHost;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
TabHost.TabSpec tab1 = tabHost.newTabSpec("First Tab");
tab1.setIndicator("First Tab");
tab1.setContent(new Intent(this,MainActivity2.class));
tabHost.addTab(tab1);

这是我尝试过的最后一件事,但它不起作用。这是我考虑过的一些链接。我找不到我做错了什么。

Example1

Example2

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.LH.tabletres.MainActivity">
    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:orientation="vertical"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent">
        </FrameLayout>

    </LinearLayout>
</TabHost>

最佳答案

我想你忘了将 android:id="@android:id/tabhost" 设置为你的 tabhost。如下图

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >........
.....
</TabHost>

关于android - TabHost 动态添加标签页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23469998/

相关文章:

android - 稍后如何设置视频文件的起点

android - 为什么Android在构建路径上找不到项目中的类?

java - 如何简单地读取我创建的 .txt 文件并计算其行数

android - Android 上的嵌套滚动

android - 当 View 模型中更新另一个 LiveData 时触发 LiveData 成员的更新

android如何从listview header中获取元素

android - ListView 不显示任何内容并隐藏数据

android - 用于平板电脑设备中数字的 EditText 输入类型,始终显示额外的键

java - 尝试打开相机导致我的应用程序崩溃

android - 无法访问 viewBinding