13

Android 12's settings' switches now look like this,

Android 12's settings screenshot

which its code is here:

https://android.googlesource.com/platform/packages/apps/Settings/+/c4cc279a2a32e6b5dfac9af4a16a4d98def82a22/res/xml/configure_notification_settings.xml#133

but neither androidx.preference.SwitchPreferenceCompat nor androidx.preference.SwitchPreference look like this in my app with updated material library (1.5.0, Material 3),

switches in my app

How can I have the same looking (and feeling, animation, etc) switches at least in Android 12 or how Android is doing it for itself? Thanks!

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81

2 Answers2

9

You can easily customize your switches to look like these.

In styles.xml add this :

<style name="App.Switches" parent="Widget.Material3.CompoundButton.Switch">
    <item name="track">@drawable/switch_track</item>
    <item name="android:thumb">@drawable/switch_thumb</item>
</style>

switch_track.xml :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item>
    <shape android:shape="rectangle">
        <solid android:color="#000000" />
        <corners android:radius="56dp" />
        <size
            android:width="64dp"
            android:height="28dp" />
    </shape>
 </item>
</layer-list>

switch_thumb.xml :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item
    android:bottom="4dp"
    android:left="4dp"
    android:right="4dp"
    android:top="4dp">
    <shape android:shape="oval">
        <solid android:color="#000000" />
        <size
            android:width="20dp"
            android:height="20dp" />
    </shape>
 </item>
</layer-list>

In the end add this line in your app's main theme to apply this style to all the switches in your app :

<item name="switchStyle">@style/App.Switches</item>
DrHowdyDoo
  • 2,327
  • 2
  • 7
  • 21
  • 6
    Thanks to your answer I now have found how that is done on Android, putting its link here so that may help others https://android.googlesource.com/platform/frameworks/base/+/172f4ac/packages/SettingsLib/SettingsTheme/res/values-v31/styles.xml#30 https://android.googlesource.com/platform/frameworks/base/+/172f4ac/packages/SettingsLib/SettingsTheme/res/drawable-v31/settingslib_switch_track.xml https://android.googlesource.com/platform/frameworks/base/+/172f4ac/packages/SettingsLib/SettingsTheme/res/drawable-v31/settingslib_switch_thumb.xml – Ebrahim Byagowi Mar 20 '22 at 00:12
2

As Material 1.7.0 the suggestion is to use MaterialSwitch which more or less is like this by default,

enter image description here

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81