无法更改开关颜色

Ask*_*skQ 3 android android-styles android-switch

我正在寻找仅将此颜色应用于所有开关.但默认情况下,它colorAccent取代了此主题进行切换.

装置:棉花糖.

布局:

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

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

我究竟做错了什么?

Eug*_*nec 9

你将风格和主题混合在一起.

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

res/values/styles.xml(不是值-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>
Run Code Online (Sandbox Code Playgroud)

然后在交换机上应用此主题叠加:

RES /布局/ layout.xml

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

<android.support.v7.widget.SwitchCompat android:theme="@style/ThemeOverlay.MySwitchCompat"/>
Run Code Online (Sandbox Code Playgroud)

选择以下两种变体之一:

  • Switch 自API 21起可用,所有主题属性都以前缀为前缀 android:
  • SwitchCompat 在appcompat-v7支持库中可用,一些主题属性没有前缀(确保你知道哪个).

  • 在与这个问题斗争了几个小时之后,只有一件事是绝对正确的:Android 上的样式和主题真是令人头疼 (2认同)