Search code examples
androidswitchcompat

Android SwitchCompat not rendering track when in off state


My question is probably best asked visually -- I want a SwitchCompat switch to look the way they do in the Android Settings app:

This is off:

enter image description here

This is on:

enter image description here

But for some reason, my SwitchCompat switch looks like this when off:

enter image description here

There is no gray "track" extending out to the right side. But, when on, it looks as expected:

enter image description here

As you can see I have applied a custom tint to my application. My custom tint was applied as follows:

<activity
    android:name=".editor.MySettingsEditor"
    android:theme="@style/Theme.MyCustomTheme" />

And then, in styles.xml:

<style name="Theme.MyCustomTheme" parent="Theme.AppCompat">    
    <item name="colorAccent">@color/myColorAccent</item>
    <item name="colorPrimary">@color/myColorPrimary</item>
    <item name="colorPrimaryDark">@color/myColorPrimaryDark</item>
    <item name="alertDialogTheme">@style/AppCompatAlertDialogStyle</item>
</style>

To ensure it was not my custom styling causing this issue, I removed it by doing this:

<activity
    android:name=".editor.MySettingsEditor"
    android:theme="@style/Theme.AppCompat" />

But still, the "off" track does not display, though the tint color now goes to the Android default teal.

enter image description here enter image description here

Why is my SwitchCompat switch missing the grey track when in the off state?

The XML that describes the SwitchCompat is super-simple:

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"/>

Thanks!


Solution

  • You can apply custom tint by setting colorControlActivated for active color and colorSwitchThumbNormal for inactive color. If you want to change track color then you can set android:colorForeground

    <style name="CustomSwitch" parent="Theme.AppCompat">  
        <!-- active thumb-->
        <item name="colorControlActivated">@color/active_switch_color</item>
    
        <!-- inactive thumb-->
        <item name="colorSwitchThumbNormal">@color/inactive_switch_color</item>
    
        <!-- inactive track color -->
        <item name="android:colorForeground">@color/inactive_track_color</item>
    </style>  
    

    In case you want to set custom theme directly to your view:

    <android.support.v7.widget.SwitchCompat
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:theme="@style/CustomSwitch"/>