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

Gue*_*OCs 8 layout android material-design material-components-android

我有一个像这样的材料切换按钮:

<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" />
Run Code Online (Sandbox Code Playgroud)

这是样式:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

jim*_*les 9

您可以使用app:thumbTint和/或app:trackTint更改开关颜色。为了获得更好的结果,定义ColorStateListin res/color(ie: res/color/custom_thumb_selector.xml) 以根据是否选中它具有不同的颜色。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>
Run Code Online (Sandbox Code Playgroud)

然后将其设置为您的风格:

<style name="ButtonStyle2" parent="Widget.MaterialComponents.CompoundButton.Switch">
    <item name="thumbTint">@color/custom_thumb_selector</item>
</style>
Run Code Online (Sandbox Code Playgroud)

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