Search code examples
androidcolorsswitchcompat

How to change the track color of a SwitchCompat


I've tried using the following link to change the color of a SwitchCompat:

How to change the color of a SwitchCompat

Notice the low constrast in my switch:

The SwitchCompat

But after changing all relevant color values the track (the brighter grey) of the SwitchCompat remains the same. I don't want to change the appearance except the color. The thumb is in pink, and I want the track to have some contrast. Did I miss to define a value in my styles.xml?

I tried these values (random non-white colors):

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/first</item>
    <item name="colorPrimaryDark">@color/second</item>
    <item name="colorAccent">@color/third</item>
   ...
    <item name="colorControlActivated">@color/first</item>
    <item name="colorControlHighlight">@color/first</item>
    <item name="colorControlNormal">@color/second</item>
    <item name="colorSwitchThumbNormal">@color/second</item>
    <item name="colorButtonNormal">@color/second</item>
...>

Solution

  • I had same probrem and solved it.

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       ...
       <!-- Active thumb color & Active track color(30% transparency) -->
       <item name="colorControlActivated">@color/theme</item>
       <!-- Inactive thumb color -->
       <item name="colorSwitchThumbNormal">@color/grey300</item>
       <!-- Inactive track color(30% transparency) -->
       <item name="android:colorForeground">@color/grey600</item>
       ...
    </style>
    

    I read app compat code, and understand it.

    android.support.v7.internal.widget.TintManager.java

    private ColorStateList getSwitchTrackColorStateList() {
        if (mSwitchTrackStateList == null) {
            final int[][] states = new int[3][];
            final int[] colors = new int[3];
            int i = 0;
    
            // Disabled state
            states[i] = new int[] { -android.R.attr.state_enabled };
            colors[i] = getThemeAttrColor(android.R.attr.colorForeground, 0.1f);
            i++;
    
            states[i] = new int[] { android.R.attr.state_checked };
            colors[i] = getThemeAttrColor(R.attr.colorControlActivated, 0.3f);
            i++;
    
            // Default enabled state
            states[i] = new int[0];
            colors[i] = getThemeAttrColor(android.R.attr.colorForeground, 0.3f);
            i++;
    
            mSwitchTrackStateList = new ColorStateList(states, colors);
        }
        return mSwitchTrackStateList;
    }