在Android中,谷歌已经提供了对于按钮水波纹效果的一个实现。在组件的中添加以下代码即可实现:
超出组件边框(但不超出父类视图),此时水波纹效果为圆形:
android:background="?android:attr/selectableItemBackgroundBorderless"
不超出组件边框,水波纹效果为组件的形状:
android:background="?android:attr/selectableItemBackground"
然而,这些效果并不一定符合我们的需求。比如,我们需要在不超出组件边框的情况下实现圆形水波纹效果,用上面两种实现方式效果分别如下:
可以看出这种实现方式达不到我们所需求的效果。这时候,我们可以使用Ripple来实现我们对应的需求。
在res/drawable中创建对应的xml文件(此处实例为button_ripple.xml):
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@android:color/holo_green_light">
<item>
<shape android:shape="oval">
<solid android:color="#aacccccc"/>
</shape>
</item>
</ripple>
<ripple>标签内的color属性是必须写上的,这个颜色值为水波纹的效果颜色;<item>标签中利用<shape>标签的shape属性设置所需的形状,<solid>标签中的颜色属性对应按钮背景色。
在组件的background属性中使用:
<ImageButton
android:background="@drawable/button_ripple"
android:layout_centerInParent="true"
android:src="@drawable/play_btton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
最终效果如下: