Search code examples
androidandroid-toolbarandroid-tablayout

TabLayout Icon Tint Changing Other Activities Actionbar Icon Tint


I have a TabLayout with Icons that are tinted to match the theme (light or dark) using the textColorPrimary theme attribute. But when I apply this color tint to my TabLayout icons in my MainActivity, The Toolbar Icons from a different activity change as well.

The Screenshots show that the icons in the TabLayout match the color of those in the activity. But the activity icons are meant to be white.

TabLayout Icons: enter image description here

Seperate Activity Toolbar Icons enter image description here

Code for setting TabLayout Icons and Text Color:

        ColorStateList colors;
    if (Build.VERSION.SDK_INT >= 23) {
        colors = getResources().getColorStateList(color.tablayout_icon_colors, getTheme());
    }
    else {
        colors = getResources().getColorStateList(color.tablayout_icon_colors);
    }
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        TabLayout.Tab tab = tabLayout.getTabAt(i);
        Drawable tabicon = tab.getIcon();
        CharSequence tabtitle = tab.getText();
        LinearLayout tabLayout2 = (LinearLayout)((ViewGroup) tabLayout.getChildAt(0)).getChildAt(tab.getPosition());
        TextView tabTextView = (TextView) tabLayout2.getChildAt(1);
        if (tabicon != null) {
            tabicon = DrawableCompat.wrap(tabicon);
            DrawableCompat.setTintList(tabicon, colors);
        }
        if (tabtitle != null) {
            tabTextView.setTextColor(colors);
        }
    }

tablayout_icon_colors.xml

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="?attr/colorAccent"
        android:state_selected="true" />
    <item android:color="?android:attr/textColorPrimary" />
</selector>

All I have in the seperate Activity to inflate the menu is this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.preview, menu);
    return true;
}

Solution

  • The problem was that the icons used as examples in the TabLayout were the same drawable icons as the ones in the other activity, and when the tint was applied, it was applied to the icon drawable and not just the view of the icons in the TabLayout.

    The fix was to simply use my actual intended icons for the TabLayout (different ones to the arrow and save icon used in the activity). So that the activity's drawable icons weren't affected. Kinda dumb of me but eh.