尝试更改文本颜色时,TabLayout.setTabTextColors()无法正常工作

问题描述 投票:8回答:4

我有一个工作TabLayout,我正在尝试动态更新选项卡文本颜色,更改选项卡时。为此,我在我的TabLayout上调用setTabTextColors()方法:

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        tabLayout.setTabTextColors(newColorStateList);
    }

    (...)
});

由于某种原因,文本颜色不会更新。有谁知道如何动态更新标签文本颜色?

我正在使用Design Support Library v22.2.0。

android android-support-library android-design-library android-tablayout
4个回答
4
投票

它最终在设计支持库22.2.1中得到修复。

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
          @Override
          public void onTabSelected(TabLayout.Tab tab) {
            tabLayout.setTabTextColors(getResources().getColor(R.color.normal), getResources().getColor(R.color.selected));

            try {
                // FIXME: 20.7.2015 WORKAROUND: https://code.google.com/p/android/issues/detail?id=175182 change indicator color
                Field field = TabLayout.class.getDeclaredField("mTabStrip");
                field.setAccessible(true);
                Object value = field.get(tabLayout);

                Method method = value.getClass().getDeclaredMethod("setSelectedIndicatorColor", Integer.TYPE);
                method.setAccessible(true);
                method.invoke(value, getResources().getColor(R.color.selected));
            } catch (Exception e) {
                e.printStackTrace();
            }
          }

        ...
        }

4
投票

经过一些调查后,似乎TabLayout内部的文本视图在创建后没有更新颜色。

我想出的解决方案是通过TabLayout的子视图并直接更新它们的颜色。

public static void setChildTextViewsColor(ViewGroup viewGroup, ColorStateList colorStateList) {
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);

        if (child instanceof ViewGroup) {
            setChildTextViewsColor((ViewGroup) child, colorStateList);
        } else if (child instanceof TextView) {
            TextView textView = (TextView) child;
            textView.setTextColor(colorStateList);
        }
    }
}

然后,在OnTabSelectedListener中:

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            setChildTextViewsColor(tabLayout, newColorStateList);
        }

        (...)
    });

2
投票

TabLayout有这样的方法 -

setTabTextColors(int normalColor, int selectedColor)

请记住,int不是颜色资源值,而是int从十六进制解析

例如:

tabLayout.setTabTextColors(Color.parseColor("#D3D3D3"),Color.parseColor("#2196f3"))

0
投票

另外,请确保不要使用单独的xml文件来设置选项卡样式。像这样的东西,就像我有(custom_tab.xml):

    TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
    tabOne.setText(R.string.tab_response);
    tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_bar_icon_response, 0, 0);
    tabLayout.getTabAt(0).setCustomView(tabOne); 
© www.soinside.com 2019 - 2024. All rights reserved.