在代码中设置所选项目时,Tablayout的文本颜色不会更改

时间:2016-02-24 08:55:56

标签: android android-tablayout

我正在尝试让tabLayout更改它的选定标签。

viewPager = (ViewPager) findViewById(R.id.configuration_sheet_pager);
    tabLayout = (TabLayout) findViewById(R.id.configuration_sheet_tabs);
    view.setSelectedTabIndicatorColor(selectedColor);
    view.setTabTextColors(normallColor, selectedColor);
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

选择标签:

//Does not work; indicator moves but text color is not affected
viewPager.setCurrentItem(change.value, change.animated);
//works as expected
tabLayout.setScrollPosition(change.value,0f,true);
viewPager.setCurrentItem(change.value);

我正在使用Android Design支持库23.1.1。我发现了一个错误吗?

2 个答案:

答案 0 :(得分:1)

如果你想在选择tabLayout xml时想要TabLayout颜色变化,那么xml应该是这样的:

  <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_primary"
        app:tabGravity="fill"
        app:tabIndicatorColor="#f32"
        app:tabIndicatorHeight="4dp"
        app:tabMode="fixed"/>

并致电

tabLayout.setupWithViewPager(viewPager);

执行以下操作:

pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

答案 1 :(得分:0)

在Material TabLayout中添加:

应用程式:tabTextColor =&#34; @颜色/ normal_color&#34;

应用程式:tabSelectedTextColor =&#34; @颜色/ selected_color&#34;

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabTextAppearance="@style/CustomTabText"
            app:tabTextColor="@color/text_color"
            app:tabSelectedTextColor="@color/text_color"
            app:tabMode="fixed" />

对于自定义TabLayout,请在getView()方法中添加:

tabTitleView.setTextColor(getResources().getColorStateList(R.drawable.selector_textview));

在drawable selector_textview.xml中添加:

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

</selector>