How to change the track color of a SwitchCompat

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

Leave a Comment