无法更改开关颜色 [英] Unable to change switch color

查看:113
本文介绍了无法更改开关颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻求将此颜色仅应用于所有开关。但是默认情况下,它会使用 colorAccent 代替此主题进行切换。

I'm looking for applying this color to all switches only. But by default, it is taking colorAccent instead of this theme for switch.

设备:棉花糖

布局:

<Switch
            android:id="@+id/soundSwitch"
            style="@style/SwitchStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginBottom="@dimen/large_space"
            android:layout_marginRight="@dimen/medium_space"
            android:layout_marginTop="@dimen/large_space"
            android:checked="true"
            />

styles-v21:

styles-v21:

<style name="SwitchStyle" parent="Theme.AppCompat.Light">
        <!-- active thumb & track color (30% transparency) -->
        <item name="android:colorControlActivated">@color/switch_color</item>

        <!-- inactive thumb color -->
        <item name="colorSwitchThumbNormal">#f1f1f1</item>

        <!-- inactive track color (30% transparency) -->
        <item name="android:colorForeground">#42221f1f</item>
    </style>

我在做什么错了?

推荐答案

您正在将样式主题混合在一起。

You're mixing styles and themes together.

这些属性是主题属性,因此在主题叠加层中一起定义它们:

These attributes are theme attributes so define them together in a theme overlay:

res / values / styles.xml (不是values-v21)

res/values/styles.xml (not values-v21)

<style name="ThemeOverlay.MySwitch" parent="">
    <item name="android:colorControlActivated">@color/switch_color</item>
    <item name="android:colorSwitchThumbNormal">#f1f1f1</item>
    <item name="android:colorForeground">#42221f1f</item>
</style>

<style name="ThemeOverlay.MySwitchCompat" parent="">
    <item name="colorControlActivated">@color/switch_color</item>
    <item name="colorSwitchThumbNormal">#f1f1f1</item>
    <item name="android:colorForeground">#42221f1f</item>
</style>

然后在开关上应用此主题覆盖:

And then apply this theme overlay on the switch:

res / layout / layout.xml

<Switch android:theme="@style/ThemeOverlay.MySwitch"/>

<android.support.v7.widget.SwitchCompat android:theme="@style/ThemeOverlay.MySwitchCompat"/>

选择以下两种变体之一:

Pick one of the two variants:


  • Switch 自API 21开始可用,所有主题属性均以 android:

  • SwitchCompat 可在appcompat-v7支持库中使用,某些主题属性未添加前缀(请确保您知道哪个)。

  • Switch available since API 21, all theme attributes are prefixed with android:
  • SwitchCompat available in appcompat-v7 support library, some theme attributes are not prefixed (make sure you know which).

这篇关于无法更改开关颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆