【问题标题】:How to style google SwitchMaterial button on Android?如何在 Android 上设置 Google SwitchMaterial 按钮的样式?
【发布时间】:2020-09-16 08:32:13
【问题描述】:

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

<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 按钮的样式?我只是想改变开关颜色

【问题讨论】:

    标签: android layout material-design material-components-android


    【解决方案1】:

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

    <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

    【讨论】:

    • 您能否更新以指定我将选择器文件保存在何处以及如何将其设置到开关中?
    猜你喜欢
    • 2011-05-28
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多