Recreate switches similar to Android 12 settings
Asked Answered
P

2

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!

Predikant answered 13/3, 2022 at 12:46 Comment(0)
T
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>
Tubbs answered 19/3, 2022 at 5:49 Comment(1)
Thanks to your answer I now have found how that is done on Android, putting its link here so that may help others android.googlesource.com/platform/frameworks/base/+/172f4ac/… android.googlesource.com/platform/frameworks/base/+/172f4ac/… android.googlesource.com/platform/frameworks/base/+/172f4ac/…Predikant
P
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

Predikant answered 4/7, 2022 at 17:46 Comment(2)
You cannot include such a control in the preference files, what are you on about?Dewees
In face the above screenshot was from preferences screen, I've explained here how stackoverflow.com/a/73782598Predikant

© 2022 - 2024 — McMap. All rights reserved.