最近在公司的Android项目中需要用到Material Design设计规范,由于其中Material Button的原生属性中仅提供纯色背景设置,当设置了自定义背景时则失去水波纹的点击效果。想要实现自定义背景(如渐变色)的点击波纹效果,必须用到ImageButton来设置点击效果与颜色。下面提供一个解决方案,可以比较好的实现自定义背景的仿Material Button:
<ImageButton
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_centerInParent="true"
android:background="@color/white"
android:clickable="false"
android:foreground="@drawable/bg_white"
android:src="@drawable/btn_blue_bg" />
接下来就是foreground属性的值bg_white,用来设置点击水波纹的圆角度和颜色。由于用到了theme references,所以记得建立在drawable-v21文件夹下:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/white">
<item android:id="@android:id/mask">
//使用水波纹控件的圆角
<shape android:shape="rectangle">
//圆角度
<corners android:radius="4dp" />
//默认的背景颜色
<solid android:color="?android:attr/colorAccent" />
</shape>
</item>
</ripple>
最后则是背景里的btn_blue_bg,也就是在这里根据UI图设置渐变颜色:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="135"
android:endColor="#3D37B8"
android:startColor="#3C72CE"
android:type="linear"
android:useLevel="true" />
<corners android:radius="4dp" />
</shape>
通过上面的设置后即可以完成自定义水波纹效果(大小,颜色)的Material Design风格的按钮。