【问题标题】:how to add icon and Image in Tabhost android?如何在 Tabhost android 中添加图标和图像?
【发布时间】:2015-06-10 05:35:58
【问题描述】:

我正在关注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

这里需要一些帮助...

【问题讨论】:

  • 你能发布整个错误日志吗?
  • 当然...我的错误看起来像这样i.imgur.com/UPoDCv3.jpg
  • 你看到你的TabSpec spec2了吗,你没有设置setContent spec2..你又设置了spec 1,我找不到任何其他问题。
  • 感谢 Sree 指出,但 Tab 中的图像图标仍未显示...我收到以下结果 imgur.com/1LqqdMq

标签: android android-tabhost tabbar android-framelayout tabwidget


【解决方案1】:

创建一个选择器 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 这些是图标图像,将在选择和取消选择选项卡时显示

【讨论】:

  • Intent().setClass(this,YourClass.class)的目的是什么; @Clairvoyant ....它抛出 IllegalStateException。就我而言
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 2014-04-10
相关资源
最近更新 更多