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

You can use:
android:foreground="?attr/selectableItemBackground"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With