且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何动态更改 Viewpager 选项卡颜色?

更新时间:2023-01-05 19:57:02

There is tutorial Styling tabs in the Android action bar. You can choose your parent theme as Theme.Holo for API>=3, or Theme.AppCompat for support library V7, etc.

And besides, for <item name="android:background">, you could set it to a selector you create for tab state change:

android:background="@drawable/selector_tab"

For selector_tab can be like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/pressed_color"
       android:state_pressed="true" />
    <item android:color="@color/selected_color"
       android:state_selected="true" /> 

    <item android:color="@color/normal_color" />
</selector>


[UPDATE]

For change tab color dynamically, suggest to use custom view with tab:

//your_custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  >


  <TextView
    android:id="@+id/tab_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:maxLines="1" />

</LinearLayout>

LinearLayout customView = (LinearLayout) getLayoutInflater().inflate(R.layout.your_custom_tab, null);

then setCustomeView(customView) when add tab to ActionBar. And in your tab/page change listener:

Tab selectedTab = yourActionBar.getSelectedTab();
View tabView = selectedTab.getCustomView();
tabView.setBackgroundColor(your_select_color);  


To remove possible gap around tab caused by custom view, you can set tab style:

<style name="ActionBarTabStyle" parent="@android:style/Widget.AppCompat.Light.ActionBar.TabView">
   <item name="android:paddingLeft">0dp</item>
   <item name="android:paddingRight">0dp</item>
   <item name="android:paddingTop">0dp</item>
   <item name="android:paddingBottom">0dp</item>
</style>

and use your theme parent accordingly.

Hope this help!