Search code examples
androidandroid-support-libraryandroid-design-libraryandroid-tablayout

TabLayout.setTabTextColors() not working when trying to change text color


I have a working TabLayout, and I am trying to update the tab text color dynamically, when changing tabs. To do this, I call the setTabTextColors() method on my TabLayout as such:

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

    (...)
});

For some reason, the text color doesn't update. Does anyone know how to update the tab text color dynamically?

I am using the Design Support Library v22.2.0.


Solution

  • It's finally fixed in Design Support Library 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();
                }
              }
    
            ...
            }