选项卡中的图标未显示出来

20

我刚开始学习Android,尝试用一个图标和文本构建TabHost,但只有文本可见。如果我将文本留空,则可以看到图标。我想同时在屏幕上看到两者。

有人能给我一些建议吗?

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Usuario usu = new Usuario();
usu.nombre = "fsdf";
lista.add(usu);

adaptador = new AdaptadorCelda(this,lista);
ListView lstView = (ListView)findViewById(R.id.lista);
lstView.setAdapter(adaptador);

Button btn = (Button)findViewById(R.id.btnSalva);

btn.setOnClickListener(onSave);



Resources res = getResources();

TabHost tabs=(TabHost)findViewById(R.id.tabhost);
tabs.setup();

TabHost.TabSpec spec=tabs.newTabSpec("mitab1");
spec.setContent(R.id.tab1);
spec.setIndicator("",res.getDrawable(android.R.drawable.ic_menu_rotate));


tabs.addTab(spec);

spec=tabs.newTabSpec("mitab2");
spec.setContent(R.id.tab2);
spec.setIndicator("ddd",
       res.getDrawable(android.R.drawable.presence_invisible));
tabs.addTab(spec);

tabs.setCurrentTab(0);

spec.setIndicator("",res.getDrawable(android.R.drawable.ic_menu_rotate)) In this case icon appears.

spec.setIndicator("ddd",
       res.getDrawable(android.R.drawable.presence_invisible));

这里是main.xml文件

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

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TabWidget
    android:id="@android:id/tabs"
    android:layout_width="match_parent"

    android:layout_height="wrap_content" />

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

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tab1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
       <TextView
            android:id="@+id/lblNombre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="17dp"
            android:text="Nombre"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/txtNombre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/lblNombre"
            android:layout_marginLeft="35dp"
            android:layout_toRightOf="@+id/lblNombre"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/txtApellido"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/txtNombre"
            android:layout_below="@+id/txtNombre"
            android:ems="10" />

        <TextView
            android:id="@+id/lblApellido"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/txtApellido"
            android:layout_alignParentLeft="true"
            android:text="Apellidos"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <RadioGroup
            android:id="@+id/tipos"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txtApellido"
            android:layout_marginTop="35dp"
            android:layout_toLeftOf="@+id/txtApellido" >

            <RadioButton
                android:id="@+id/rdbAlta"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="alta" />

            <RadioButton
                android:id="@+id/rdbBaja"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="baja" />

            <RadioButton
                android:id="@+id/rdbTramite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="tramite" />
        </RadioGroup>

        <Button
            android:id="@+id/btnSalva"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/txtApellido"
            android:layout_alignTop="@+id/tipos"
            android:layout_marginLeft="58dp"
            android:layout_marginTop="30dp"
            android:text="Button" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txtApellido"
            android:src="@drawable/ic_menu_chart" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/tab2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/lista"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/tipos"
            android:layout_marginTop="24dp" >
        </ListView>
    </LinearLayout>
</FrameLayout>


请提供更多信息。 - Wampie Driessen
抱歉,各位,我有点新手。 - theholy
4个回答

53

你是否在运行 Android 4.x 版本的设备上测试过你的应用程序?我最近发现,与目标设备和 Android 平台版本有关,TabHost 默认的行为会有所不同。

通过运行提供图标和文本到 setIndicator 的应用程序(如问题中源代码所示),得到以下测试结果:

  • Android 2.1 手机:图标和文本都显示出来了(预期的是图标下方的标签)
  • Android 4.0.3 手机:只有文本被显示出来了,图标没有被显示出来
  • 运行 ICS 的平板电脑:选项卡中显示了图标和文本

正如你也发现的那样,如果将标签替换成空字符串,则图标将会出现在手机上,但用户需要猜测图标的含义。除此之外,当在早期版本的 Android 上运行这个应用程序时,选项卡保持它们的大小并留下一个空白区域。

要改变这个由设备决定的选项卡应该获得多少空间的决策,我在这篇自定义选项卡的教程中找到了解决方案:

首先,你需要提供自己的选项卡指示器布局(如教程中的 "layout/tab_indicator.xml"),其中包括一个 ImageView 和一个 TextView。然后通过 setIndicator 告诉 TabSpec 使用这个布局即可。这样就可以在运行 ICS 的手机上获得图标和标签了。

下面是如何设置指示器的重要部分(其中 "this" 表示当前的活动):

TabHost.TabSpec spec = this.getTabHost().newTabSpec(tag);

View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
((TextView) tabIndicator.findViewById(R.id.title)).setText(label);
((ImageView) tabIndicator.findViewById(R.id.icon)).setImageResource(drawableResourceId);

spec.setIndicator(tabIndicator);

如果您希望在较老和较新的手机上获得相同的选项卡外观,可以在此处查看更多信息:http://jgilfelt.github.com/android-actionbarstylegenerator/。该页面生成图像和样式以自定义操作栏,包括选项卡,并帮助我了解如何定义 9 段缩放背景图像。


2
太棒了,你应该制作教程。非常易于阅读和理解。 - basickarl
还有我好像正在使用更为更新的片段。有什么想法可以将其实现到片段中而不是通过旧的TabActivity吗? - basickarl
2
这种方法还可以在选中选项卡时去除图像/文本下的“细线”。 - basickarl
回答片段方法: "mTabHost.getTabWidget()",同时记得导入 "import android.widget.ImageView"。否则它可以与片段一起工作。 - basickarl
2
你知道为什么安卓工程师对开发者们这么友好吗? - Muhammad Babar
6
这个教程似乎已经下线了,但是你仍然可以在互联网档案馆找到它:http://web.archive.org/web/20120925030428/http://ondrejcermak.info/programovani/custom-tabs-in-android-tutorial/ - rbp

9

这是一种在ICS中显示文本和图标的简单方法。在设置Tabhost之后,我调用了以下方法:

setTabIcon(mTabHost, 0, R.drawable.ic_tab1); //for Tab 1
setTabIcon(mTabHost, 1, R.drawable.ic_tab2); //for Tab 2

public void setTabIcon(TabHost tabHost, int tabIndex, int iconResource) {
    ImageView tabImageView = (ImageView) tabHost.getTabWidget().getChildTabViewAt(tabIndex).findViewById(android.R.id.icon);
    tabImageView.setVisibility(View.VISIBLE);
    tabImageView.setImageResource(iconResource);
}

如果您想要一个更高级的解决方案,您需要像@sunadorer建议的那样创建一个布局。我的建议是,您可以使用holo主题布局来创建您的布局,在您的sdk_dir/platforms/android-14/data/res/layout/tab_indicator_holo.xml 文件中搜索。

我的高级解决方案是:您需要创建这样一个布局:

tab_indicator.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="wrap_content"
              android:orientation="vertical"
              android:paddingTop="5dp"
              android:paddingBottom="5dp"
              style="@android:style/Widget.Holo.Tab">

    <ImageView
        android:id="@android:id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:visibility="visible" />

    <TextView
        android:id="@android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        style="@android:style/Widget.Holo.ActionBar.TabText" />

</LinearLayout>

在您的 Activity 或 Fragment 中,创建下一个函数:
public View createTabIndicator(LayoutInflater inflater, TabHost tabHost, int textResource, int iconResource) {
    View tabIndicator = inflater.inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
    ((TextView) tabIndicator.findViewById(android.R.id.title)).setText(textResource);
    ((ImageView) tabIndicator.findViewById(android.R.id.icon)).setImageResource(iconResource);
    return tabIndicator;
}

最后,当您在您的活动或片段中创建标签时,请使用以下代码:

mTabHost.addTab(
    mTabHost.newTabSpec("tab1")
    .setIndicator(createTabIndicator(inflater, mTabHost, R.string.tab1, R.drawable.ic_tab1))
    .setContent(R.id.tab1)
);

我已在ICS上测试过这个解决方案,效果很好。
祝好运 :)

1
我在这行代码中遇到了NPE错误:ImageView tabImageView = (ImageView) tabHost.getTabWidget().getChildTabViewAt(tabIndex).findViewById(android.R.id.icon); - user3233280
请注意,如果您有多个选项卡,则可能会看到文本换行,即使似乎有足够的空间。解决此问题的方法是在LinearLayout中设置paddingStart =“0dp”和paddingEnd =“0dp”。 - N R

5

还有另一种非常简单的解决方案。

看起来问题在于新的 Holo 主题和 TabWidget。因此,您应该在您的 values-v11 文件夹中定义 Holo 主题,但使用旧的 TabWidget 样式,例如:

<style name="MyAppTheme" parent="@android:style/Theme.Holo.NoActionBar">
    <item name="android:tabWidgetStyle">@android:style/Widget.TabWidget</item>
</style>

这对我很有效,希望能帮助到其他人。


你需要将这行代码添加到 values-v14 及更高版本的文件夹中。 - biswajitGhosh

2

我尝试以下方法来实现它,它可以正常工作:

  1. 使用 setIndicator("TAB") 来设置文本。
  2. 使用 setBackgroundDrawable(-) 来设置图标。

示例代码:

    final TabHost               tabHost = (TabHost)findViewById(android.R.id.tabhost);
    final Resources             res = getResources();
    int i;

    tabHost.setup(); //Call setup() before adding tabs if loading TabHost using findViewById(). 

    TabHost.TabSpec ts = tabHost.newTabSpec("trackinfo");
    //ts.setIndicator("", res.getDrawable(R.drawable.icon_trackinfo));
    ts.setIndicator("Track Information");
    ts.setContent(R.id.tabTrackInfo);
    tabHost.addTab(ts);

    TabHost.TabSpec ts2 = tabHost.newTabSpec("collection");
    //ts2.setIndicator("", res.getDrawable(R.drawable.icon_collection_gray));
    ts2.setIndicator("My Collection");
    ts2.setContent(R.id.tabMyCollecton);
    tabHost.addTab(ts2);

    tabHost.setOnTabChangedListener(new OnTabChangeListener(){
        @Override
        public void onTabChanged(String tabId) 
        {
            if("trackinfo".equals(tabId)) {
                //
                TabWidget tw = (TabWidget)tabHost.findViewById(android.R.id.tabs);
                View tabView = tw.getChildTabViewAt(0);
                TextView tv = (TextView)tabView.findViewById(android.R.id.title);
                tv.setTextColor(TabColor[0]);
                tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_selected));

                tabView = tw.getChildTabViewAt(1);
                tv = (TextView)tabView.findViewById(android.R.id.title);
                tv.setTextColor(TabColor[1]);

                tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_gray));
            }
            if("collection".equals(tabId)) {
                //
                TabWidget tw = (TabWidget)tabHost.findViewById(android.R.id.tabs);
                View tabView = tw.getChildTabViewAt(0);
                TextView tv = (TextView)tabView.findViewById(android.R.id.title);
                tv.setTextColor(TabColor[1]);
                tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_gray));

                tabView = tw.getChildTabViewAt(1);
                tv = (TextView)tabView.findViewById(android.R.id.title);
                tv.setTextColor(TabColor[0]);
                tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_selected));

        }
        }}); // END OF tabHost.setOnTabChangedListener

    // After Tabs being added
    // change font settings 
    TabWidget tw = (TabWidget)tabHost.findViewById(android.R.id.tabs);
    for(i=0;i<2;i++)
    {
        View tabView = tw.getChildTabViewAt(i);
        TextView tv = (TextView)tabView.findViewById(android.R.id.title);
        tv.setHeight(25);
        tv.setTextColor(TabColor[i]);
        tv.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        tv.setTextSize(20);      
        tabView.setBackgroundDrawable(res.getDrawable(TabIcon[i]));

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接