Search code examples
androidkotlinandroid-stylesmaterial-components-androidandroid-switch

Change SwitchMaterial color dinamicaly


In my app, the first activity is a selector where i can select between 3 buttons: red, green, yellow. When i select one button, a new activity is displayed with a SwitchMaterial. Now i want to change the colorControlActivated so that the switch color is red if i have selected the red button, green for the green button and so on. How can i do that?

<com.google.android.material.switchmaterial.SwitchMaterial
                        android:id="@+id/profile_setting_switch1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginEnd="20dp"
                        android:theme="@style/SwitchTecnoTheme"
                        app:layout_constraintBottom_toBottomOf="@id/profile_setting_1"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintTop_toTopOf="@id/profile_setting_1" />
<style name="SwitchTecnoTheme" >
        <item name="colorControlActivated">@color/tecno_brand_color</item>
    </style>

Solution

  • You can define 3 different selectors and use something like:

        switch.isUseMaterialThemeColors = false
        switch.thumbTintList = ContextCompat.getColorStateList(this,R.color.thumb_selector)
        switch.trackTintList = ContextCompat.getColorStateList(this, R.color.track_selector)
    

    where thumb_selector:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:state_enabled="false" android:color="@color/switchTrackDisable"/>
      <item android:state_checked="true" android:color="@color/switchThumbActive" />
      <item android:color="@color/switchThumbkNormal" />
    </selector> 
    

    and track_selector:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:state_enabled="false" android:color="@color/switchTrackDisable"/>
      <item android:state_checked="true" android:color="@color/switchTrackActive" />
      <item android:color="@color/switchTrackNormal" />
    </selector>