我有一个图像按钮,点击它时没有响应触摸动画,因为它是一个静态图像,而不像棒棒糖上的常规按钮带有内置的连锁效果。我想将材料设计波纹触摸效果添加到图像中,但似乎无法找到实现它的方法。我可以在图像上设置一个滤色器,但这不是涟漪效应。我正在尝试做的一个例子就是当你在Google Play音乐中保存一个专辑封面图像并且影像波纹在图像上移动时。
答案 0 :(得分:202)
为了获得更好的结果:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_button"
android:background="?attr/selectableItemBackgroundBorderless"
/>
答案 1 :(得分:22)
您可以像这样在ImageButton中添加背景:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/btn_dialog"
android:background="?android:attr/selectableItemBackground" />
答案 2 :(得分:4)
我从i.shadrin(here)和Nicolars(here)得到了很好的答案。
他们的回答之间的区别在于?attr/selectableItemBackgroundBorderless
可以为您提供android.view.InflateException
,因此?android:attr/selectableItemBackground
就是解决方案。
FWIW,我不知道为什么会发生异常,因为第一个答案在我所有的旧项目中运行良好,但在我最近的项目中没有(可能是因为应用主题= android:Theme.Material
?)。
正在发生的奇怪事情是,虽然显示了涟漪效应,但它已经超出了ImageButton,所以解决方案是:
android:foreground="?android:attr/selectableItemBackgroundBorderless"
代替android:background="?android:attr/selectableItemBackgroundBorderless"
希望如果你面对同样的事情会对你有帮助。
答案 3 :(得分:0)
如果您已经有背景并且不想更改它,请使用前景;
<ImageButton
android:layout_width="60dp"
android:layout_height="match_parent"
android:background="@drawable/preview_in_4k_background"
android:src="@drawable/ic_full_screen_24px"
android:layout_marginLeft="5dp"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:layout_column="2"/>
答案 4 :(得分:0)
您可以使用 MaterialButton (com.google.android.material.button.MaterialButton) 代替具有此属性的 ImageButton。 如果您使用材料组件。
<style name="IconOnlyButton">
<item name="iconPadding">0dp</item>
<item name="iconGravity">textStart</item>
</style>
<com.google.android.material.button.MaterialButton
style="@style/IconOnlyButton"
app:icon="@drawable/ic_refresh"/>
答案 5 :(得分:-1)
或者,如果您要定位API 21+,请使用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"/>