Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change switch color

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

Device: marshmallow.

layout:

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

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

What am I doing wrong?

like image 608
AskQ Avatar asked Oct 31 '17 12:10

AskQ


People also ask

How can I change background color of clicking button in Android?

Inside the function use setBackgroundResource(R. color. button_color) function, this will set the background with color button_color.


2 Answers

You're mixing styles and themes together.

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

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

<androidx.appcompat.widget.SwitchCompat
    android:theme="@style/ThemeOverlay.MySwitchCompat"/>

Pick one of the two variants:

  • Switch available since API 21, all theme attributes are prefixed with android:
  • SwitchCompat available in AndroidX AppCompat library, some theme attributes are not prefixed (make sure you know which).
like image 194
Eugen Pechanec Avatar answered Oct 18 '22 23:10

Eugen Pechanec


Probably, you can try using android.support.v7.widget.SwitchCompat instead of Switch and android:theme=@style/SwitchStyle instead of style="@style/SwitchStyle"

like image 4
Boris Kozyrev Avatar answered Oct 19 '22 01:10

Boris Kozyrev