我需要帮助,我发现在TabHost中更改背景颜色有困难.
原始图片:
我需要修改背景颜色,如下图所示.
我在我的代码和XML中尝试了很多东西,但都失败了.
我的代码如下:
TabHost tabHost = getTabHost(); // Tab 1 TabSpec aba1spec = tabHost.newTabSpec("Tab 1"); // setting Title and Icon for the Tab tabHost.getTabWidget().setStripEnabled(false); aba1spec.setIndicator("",getResources().getDrawable(R.drawable.tabenviaarq)); Intent photosIntent = new Intent(this, MainActivity.class); aba1spec.setContent(photosIntent); // Adding all TabSpec to TabHost tabHost.addTab(aba1spec); // Adding tab1
在XML中我有这个:
有人有一些想法,我非常感谢.
解决方案是使用带选择器的背景,代码在这里:
private void initTabsAppearance(TabWidget tabWidget) { // Change background for(int i=0; i < tabWidget.getChildCount(); i++) tabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg); }
tab_bg是带选择器的xml drawable:
对于完整的Tab自定义,我将添加使用自定义主题更改选项卡文本样式的代码.将其添加到styles.xml:
<style name="MyCustomTheme" parent="@android:style/Theme.Light.NoTitleBar"> <item name="android:tabWidgetStyle">@style/CustomTabWidget</item> </style> <style name="CustomTabWidget" parent="@android:style/Widget.TabWidget"> <item name="android:textAppearance">@style/CustomTabWidgetText</item> </style> <style name="CustomTabWidgetText" parent="@android:style/TextAppearance.Widget.TabWidget"> <item name="android:textSize">12sp</item> <item name="android:textStyle">bold</item> </style>
要使用此主题,请在AndroidManifest.xml中定义它:
<application android:theme="@style/MyCustomTheme">
现在你有了自定义背景和自定义文本样式的标签小部件.
tabHost.setOnTabChangedListener(new OnTabChangeListener() { public void onTabChanged(String arg0) { for (int i = 0; i < tab.getTabWidget().getChildCount(); i++) { tab.getTabWidget().getChildAt(i) .setBackgroundResource(R.drawable.tab_selected); // unselected } tab.getTabWidget().getChildAt(tab.getCurrentTab()) .setBackgroundResource(R.drawable.tab_unselected); // selected } });
尝试这种方法,我希望这会对你有所帮助.