android - 如何在 Tabhost android 中添加图标和图像?

标签 android android-tabhost tabbar android-framelayout tabwidget

我正在关注 this使用 Tabhost 添加图标和文本的教程。

我正在编写以下代码以在选项卡中添加文本和图标。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
    tabHost.setup();

    TabSpec spec1=tabHost.newTabSpec("Tab 1");
    spec1.setContent(R.id.tab1);
    spec1.setIndicator("Tab 1",getResources().getDrawable(R.drawable.home));

    TabSpec spec2=tabHost.newTabSpec("Tab 2");
    spec1.setContent(R.id.tab2);
    spec2.setIndicator("Tab 2",getResources().getDrawable(R.drawable.home));

    TabSpec spec3=tabHost.newTabSpec("Tab 3");
    spec3.setIndicator("Tab 3",getResources().getDrawable(R.drawable.home));
    spec3.setContent(R.id.tab3);

    tabHost.addTab(spec1);
    tabHost.addTab(spec2);
    tabHost.addTab(spec3);
}

仅在选项卡中添加文本时效果很好,但会抛出以下错误消息

java.lang.IllegalArgumentException: you must specify a way to create the tab content at android.widget.TabHost.addTab

这里需要一些帮助...

最佳答案

创建一个选择器 xml 将其存储在可绘制文件夹中并尝试此代码:

TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;

intent = new Intent().setClass(this,YourClass.class);
spec = tabHost.newTabSpec("tab_name").setIndicator("Tab Text", getResources().getDrawable(R.drawable.tab_selector)).setContent(intent);
tabHost.addTab(spec);

选择器的 Xml 名称为 tab_selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:state_pressed="false"
        android:drawable="@drawable/ic_tab_selected" />
    <item android:drawable="@drawable/ic_tab_unselected" />
</selector>

ic_tab_selected 和 ic_tab_unselected 这些是将在选择和取消选择选项卡时显示的图标图像

关于android - 如何在 Tabhost android 中添加图标和图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30747865/

相关文章:

Android Eclipse,两个不同选项卡中的两个 Activity ,不断调用 onCreate()!

ios - 检查 tabBar 是否为 nil

java.lang.RuntimeException : Failure delivering result ResultInfo{who=null, 请求=2,结果=-1,数据= Intent

java - Android:如何使用 Volley::Error 向服务器发送 header 请求

android - 选项卡中的图标不显示!!!我应该怎么办?

android - 在 android 选项卡布局中显示进度对话框

iPhone 标签栏上的未读计数

ios - 更新 Xcode 11 和 IOS 13 后 Tabbar 按钮插入错误

android - 调试 FFmpeg

java - 记录器输出到字符串