Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style google SwitchMaterial button on Android?

I have a material switch button like this:

<com.google.android.material.switchmaterial.SwitchMaterial
                android:id="@+id/effectEnabled"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                style="@style/ButtonStyle2"
                android:checked="true"
                android:enabled="true" />

here's the style:

<style name="ButtonStyle2" parent="Base.Widget.AppCompat.Button">
        <!--<item name="android:fontFamily">sans-serif-light</item>-->
        <!--<item name="android:textStyle">bold</item>-->
        <item name="android:textColor">@color/colorPrimary</item>
        <item name="android:textSize">20sp</item>
        <item name="android:textAllCaps">false</item>
    </style>

with these styles, the button gets broken and with a square background of grey color.

How can I style SwitchMaterial buttons? I just want to change the switch color

like image 391
Guerlando OCs Avatar asked May 28 '20 21:05

Guerlando OCs


1 Answers

You can use app:thumbTint and/or app:trackTint to change the switch colors. For better results define a ColorStateList in res/color (ie: res/color/custom_thumb_selector.xml) to have differente colors based on if it is checked or not. ie:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="@color/customChecked" />
    <item android:color="@color/customUnchecked" />
</selector>

and then set it in your style:

<style name="ButtonStyle2" parent="Widget.MaterialComponents.CompoundButton.Switch">
    <item name="thumbTint">@color/custom_thumb_selector</item>
</style>

Note: Your custom style should inherit from Widget.MaterialComponents.CompoundButton.Switch

like image 148
jimmymorales Avatar answered Nov 08 '22 23:11

jimmymorales