在 Android 应用程序(最小 sdk 11,目标 sdk 18)上,扩展 Fragment 的类应该创建带有一个标签和一个图标的 TabHost 选项卡 (TabSpec)。但是……
TabSpec ts1;
// if the label is set to "Home", the label is displayed but not the image
ts1 = tab_host.newTabSpec("TAB_ONE").setIndicator("Home", getActivity().getResources().getDrawable(R.drawable.ic_tabone)).setContent(R.id.edit_species_tab);
// if the label is null or empty, the image is displayed
ts1 = tab_host.newTabSpec("TAB_ONE").setIndicator(null, getActivity().getResources().getDrawable(R.drawable.ic_tabone)).setContent(R.id.edit_species_tab);
据我所知documentation没有提到标签和图标是互斥的。
起初我以为标签有纯色背景色隐藏了图标,但事实并非如此。事实上,当我设置 TabHost 背景时,我可以看到标签是透明的:
tab_host.getTabWidget().setBackgroundResource(R.drawable.ic_mybackground);
如何设置 TabSpec 背景,以便为每个选项卡显示标签和图标?
tab_host.xml
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="65dp" >
<LinearLayout
android:id="@+id/edit_species_tab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>
<LinearLayout
android:id="@+id/edit_regions_tab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>
<LinearLayout
android:id="@+id/edit_quiz_tab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>
<LinearLayout
android:id="@+id/edit_about_tab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>
</FrameLayout>
最佳答案
在holo主题中,tab只支持label或者icon,并且互斥。
在Holo之后,tab默认只有label,请查看design guideline。 http://developer.android.com/design/building-blocks/tabs.html
如果您愿意同时添加标签和图标,有两种选择。
选项 1:使用旧的 Gingerbread 主题。设置你的 android:targetSdkVersion 9 或以下。 (蜂窝之前)
选项 2:为您的选项卡使用自定义布局和 View 。当然,这需要一些努力,但您可以根据需要使用任何自定义布局。例如:
在您的 Activity 代码中:
TabHost.TabSpec ts1;
View tabView = getLayoutInflater().inflate(R.layout.custom_tab, tab_host, false);
ts1 = tab_host.newTabSpec("TAB_ONE").setIndicator(tabView).setContent(R.id.edit_species_tab);
在你的布局中:(任何你想要的)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
</LinearLayout>
关于android - TabHost TabSpec setIndicator 中的标签和图标是否相互排斥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18776694/