问题
I have an imagebutton that doesn't respond with a touch animation when it is clicked because it is a static image unlike regular buttons on lollipop which come with the built in ripple effect. I would like to add the material design ripple touch effect to the image but can't seem to find a way to implement it. I can set a color filter over the image but that is not the ripple effect. An example of what I'm trying to do is when you hold an album cover image in Google Play Music and a shadow ripple moves across the image.
回答1:
For even better result:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_button"
android:background="?attr/selectableItemBackgroundBorderless"
/>
回答2:
You can just add a background to your ImageButton like this :
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/btn_dialog"
android:background="?android:attr/selectableItemBackground" />
回答3:
I got good answers from i.shadrin (here) and Nicolars (here).
The difference between their answers is that ?attr/selectableItemBackgroundBorderless
can give you an android.view.InflateException
, so the ?android:attr/selectableItemBackground
is the solution.
FWIW, I do not know why the exception happens, because the first answer worked fine in all my old projects, but in my recent project not (maybe because the app theme = android:Theme.Material
?).
The strange thing that was happening is that though the ripple effect was shown it was out-bounding the ImageButton, so the solution is:
- To use the
android:foreground="?android:attr/selectableItemBackgroundBorderless"
instead ofandroid:background="?android:attr/selectableItemBackgroundBorderless"
Hope it help you if you are facing the same.
回答4:
Or, alternatively, if you're targeting API 21+, use backgroundTint
:
<ImageButton
android:backgroundTint="@color/white"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/ic_button"
style="@style/Widget.AppCompat.ImageButton"/>
来源:https://stackoverflow.com/questions/30959610/apply-material-design-touch-ripple-to-imagebutton