正如mbaird所提到的,更好的解决方案是使用带有选择器的background,这样你就不必检查onTabChanged
并进行手动更新。最简代码如下:
private void initTabsAppearance(TabWidget tabWidget) {
for(int i=0; i < tabWidget.getChildCount(); i++)
tabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg);
}
其中tab_bg
是一个带有选择器的XML可绘制对象:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/tab_bg_selected" />
<item android:drawable="@drawable/tab_bg_normal" />
</selector>
要完全自定义选项卡,我将添加更改使用自定义主题的选项卡文本样式的代码。 将其添加到styles.xml
中:
<resources>
<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>
</resources>
要使用这个主题,在AndroidManifest.xml中定义它:
<application android:theme="@style/MyCustomTheme">
现在您拥有带有自定义背景和自定义文本样式的选项卡小部件。