6

I need to change SwitchCompat's track color. I've tried this, but it didn't worked for me. This is code of my XML file

<android.support.v7.widget.SwitchCompat
    android:id="@+id/sc_push"
    style="@style/switchStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:theme="@style/switchStyle"
    app:theme="@style/switchStyle" />

and this is my style.xml file

<style name="switchStyle">
    <item name="colorControlActivated">@color/red</item>
    <item name="android:colorForeground">@color/gray</item>
</style>

What seems the problem?

In addition, I can't change the activity's color or base application's color. I have to change color for this single view.

Community
  • 1
  • 1
Alfred Woo
  • 569
  • 1
  • 4
  • 21

2 Answers2

14

Try this code.

 <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>
Jiks
  • 1,589
  • 2
  • 11
  • 14
1

The better way to do it would be,

  1. Create new resource file as below, switch_track_color.xml, using selector tag.
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="#15A215" android:state_checked="true"/>
    <item android:color="#BAC7CB" android:state_checked="false"/>

</selector>
  1. Use this in style for SwitchCompat.
<style name="SwitchStyle">
   <item name="thumbTint">#ffffff</item>
   <item name="trackTint">@color/switch_track_color</item>
</style>
Elikill58
  • 3,190
  • 22
  • 17
  • 38