Search code examples
androidxmlkotlin

How to set MaterialSwitch thumbTint programmatically


I've implemented a function to change the themes in my app, before I had multiple themes I used a selector with different states for the MaterialSwitch like this:

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

This will be added to the switch in the layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <com.google.android.material.materialswitch.MaterialSwitch
       android:id="@+id/sw_update_list"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       app:thumbTint="@drawable/thumb_style"
       android:layout_alignParentEnd="true"
       android:layout_centerInParent="true"
       android:checked="true" />

</RelativeLayout>

How ca I do this programmatically?


Solution

  • Sooo, I figured it out by myself.

     val thumbTintSelector = ColorStateList(
                arrayOf(
                    intArrayOf(android.R.attr.state_checked),
                    intArrayOf(-android.R.attr.state_checked)
                ),
                intArrayOf(
                    // Color when the switch is checked
                   Color.parseColor("#000000"),
                    // Color when the switch is unchecked
                     Color.parseColor("#938F99")
                )
            )
            switchUpdatelist.thumbTintList = thumbTintSelector