For people using Kotlin, this is an extended version of @Nicolas answer. If you are using CardView
, you need to change the foreground
, not the background
.
Code
fun View.addBackgroundRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
setBackgroundResource(resourceId)
}
fun View.addBackgroundCircleRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
setBackgroundResource(resourceId)
}
fun View.addForegroundRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
foreground = ContextCompat.getDrawable(context, resourceId)
}
fun View.addForegroundCircleRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
foreground = ContextCompat.getDrawable(context, resourceId)
}
Usage
// Background ripple
linearLayout.addBackgroundRipple()
// Foreground ripple
cardView.addForegroundRipple()