- minSdkVersion 23+
android:foreground=?android:attr/selectableItemBackground for each view.
- minSdkVersion 21
There is only FrameLayout (and CardView) that supports the foreground attribute. If you want ripple effect on the FrameLayout, it’s still able to use
android:foreground=?android:attr/selectableItemBackground for the ripple effect.
For other layouts, they can use
android:background=?android:attr/selectableItemBackground but the ripple effect will be covered by child views.
One solution but I don’t support is to add one dummy FrameLayout with
RippleDrawable shows a ripple effect in response to state changes. And more, if we want a perfect ripple effect on API 21+, it’s strongly recommended adding ripple drawable in the foreground, because it will make ripple effect above other child views, especially when this view has its own background.
Although RippleDrawable was added in API level 21, attribute foreground is fully supported in View in API 23+, only FrameLayout in API 21+ supported foreground, so CardView extends FrameLayout and works well with foreground in API 21+.
Just use android:foreground=?android:attr/selectableItemBackground is enough to implement this effect.
Don’t forget to set clickable because the ripple effect comes after the click event.
By the way, what’s the difference between “?attr/” and “?android:attr/” in android? Android Arsenal has the answer:
Defines and refers to the value of an attribute which you have defined on your own in your application.
Refers to the values of an attribute which are already available in android built-in. More specifically, the ? implies an extra level of indirection. Think of it as