如何在 Android 上设置 google SwitchMaterial 按钮的样式?

How to style google SwitchMaterial button on Android?

我有一个 material 开关按钮,如下所示:

<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" />

样式如下:

<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>

使用这些样式,按钮会损坏并带有灰色方形背景。

如何设置 SwitchMaterial 按钮的样式?我只是想改变开关颜色

您可以使用app:thumbTint and/or app:trackTint 来改变开关颜色。 为了获得更好的结果,请在 res/color 中定义一个 ColorStateList(即:res/color/custom_thumb_selector.xml),以根据是否选中来使用不同的颜色。 即:

<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>

然后按照您的风格进行设置:

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

注意:您的自定义样式应继承自 Widget.MaterialComponents.CompoundButton.Switch