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

4
我正在尝试更改选定的选项卡,以便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设计支持库23.1.1。我是否发现了一个错误?
2个回答

1
如果您希望在选中选项卡时更改TabLayout的颜色,则 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) {

            }
        });

0
在 Material TabLayout 中添加以下内容:

app:tabTextColor="@color/normal_color"

app:tabSelectedTextColor="@color/selected_color"

<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接