正如mbaird提到的,更好的解決方案是使用背景與選擇器,所以你不必檢查onTabChanged
並做手動更新。最小的代碼是在這裏:
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繪製與選擇:
<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">
現在你有自定義背景和自定義文本樣式標籤控件。
非常感謝,這真的幫助了我。有沒有什麼辦法在XML中實現這種方法? – teoREtik 2011-04-04 07:58:20
@teoREtik XML是靜態內容,僅適用於您的活動首次啓動時(佈局初始化),因此不會。 – Blundell 2011-10-23 15:55:36
感謝您的幫助..這個答案是非常有用的.. +1爲.. ..乾杯.. !! – Aditya1510 2012-11-17 05:49:45