TabLayout更改tabText颜色

时间:2016-11-03 22:28:37

标签: java android tabs styles android-tablayout

我试图让选定的标签只有不同的颜色,请参阅以下代码,

viewPager =(ViewPager)findViewById(R.id.pager);

    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Chats "));
    tabLayout.addTab(tabLayout.newTab().setText("Services"));
    tabLayout.addTab(tabLayout.newTab().setText("Favourite"));
    tabLayout.setTabTextColors(-1,-256);
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));


    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

我的xml:

<android.support.design.widget.TabLayout
    android:layout_height="?attr/actionBarSize"
    android:layout_width="match_parent"
    android:id="@+id/tab_layout"
    style="@style/MyCustomTabLayout"
    />

和我的风格:

 <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabTextAppearance">@style/MyCustomTabText</item>
    <item name="tabSelectedTextColor">@color/colorAccent</item>
</style>

<style name="MyCustomTabText" parent="TextAppearance.AppCompat.Button">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@color/theme_blue</item>
</style>

请帮帮我,看看哪些需要编辑,以便一次只有一个标签有不同的颜色!

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以使用app:tabTextColor和app:tabSelectedTextColor

来完成此操作

像这样:

<android.support.design.widget.TabLayout
  android:layout_height="?attr/actionBarSize"
  android:layout_width="match_parent"
  android:id="@+id/tab_layout"
  app:tabTextColor="@color/theme_blue"
  app:tabSelectedTextColor="@color/colorAccent"
  style="@style/MyCustomTabLayout"/>