Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ripple effect of preference switch on SwitchMaterial?

The switches in PreferenceScreen have nice ripple effects that go over the complete width. How can I get this ripple effect on a SwitchMaterial switch that is outside of a PreferenceScreen (in a normal layout)?

like image 942
stefan.at.wpf Avatar asked Oct 23 '25 19:10

stefan.at.wpf


2 Answers

Touches on the ViewGroup whether directly on the ViewGroup or a child flow from the ViewGroup to the child and back down. I find this post and its associated Stack Overflow answer helpful in understanding touch events.

To get the PreferenceScreen ripple effect, set up the layout with the parent layout of the switch as clickable and focusable with a ripple background.

We will want the same response whether the switch or the ViewGroup is directly touched. The switch has its own responsive background, so the background of the switch is set to @null so it is not highlighted on touch events. This can be removed if the highlighting is desired.

<LinearLayout 
    android:id="@+id/switchLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:padding="16dp">

    <com.google.android.material.switchmaterial.SwitchMaterial
        android:id="@+id/switchWidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@null"
        android:clickable="false" />
</LinearLayout>

Since the switch will not receive click events because the parent is capturing them, we must programmatically click the switch when the ViewGroup is clicked:

val switchLayout = findViewById<ViewGroup>(R.id.switchLayout)
switchLayout.setOnClickListener {
    findViewById<View>(R.id.switchWidget).performClick()
}

This all will give us the following:

enter image description here

like image 169
Cheticamp Avatar answered Oct 26 '25 08:10

Cheticamp


You can use:

android:foreground="?attr/selectableItemBackground"
like image 44
Pavel Poley Avatar answered Oct 26 '25 07:10

Pavel Poley