Alex Wilson
Alex Wilson

Reputation: 1853

How can I add a background color to an Android SwitchPreference?

I am using a PreferenceFragment to inflate an xml file with a single SwitchPreference. How can I make the background color of that preference including the title of the SwitchPreference to match the image below. I have tried setting the background but I am only able to set the background color of the switch icon.

enter image description here

Upvotes: 3

Views: 1110

Answers (2)

Lakmal Weerasekara
Lakmal Weerasekara

Reputation: 72

styles.xml (make this style in style.xml file in values folder)

<resources>

<style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <!-- switch on thumb & track color -->
    <item name="colorControlActivated">#02c754</item>

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

    <!-- switch off track color -->
    <item name="android:colorForeground">#42221f1f</item>
</style>

</resources>

your_layout_activity.xml

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switch_on_off"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_gravity="center"
    android:checked="true"
    android:gravity="center"
    android:paddingLeft="30dp"
    android:theme="@style/SwitchTheme"
    app:switchMinWidth="55dp"/>

this source is worked for me. Try with this you will get understand

Upvotes: 1

Amjad Khan
Amjad Khan

Reputation: 1317

I have done this using the style

Style.xml

<style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <item name="colorControlActivated">@color/yourcolor</item>
</style>

in Layout

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switch_on_off"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_gravity="center"
    android:checked="false"
    android:gravity="center"
    android:paddingLeft="@dimen/padding"
    android:paddingRight="@dimen/padding"
    app:switchMinWidth="@dimen/switch_size"
    app:theme="@style/SwitchTheme" />

Upvotes: 0

Related Questions