水波纹效果从Android5.0就已经出来了,基本的使用相信你们都知道了,这里多谈一些相对深层次的使用:html
android:background="?android:attr/selectableItemBackground"
复制代码
以控件宽高中最大的数值做为水波纹效果所在正方形的边界进行绘制java
android:background="?android:attr/selectableItemBackgroundBorderless"
复制代码
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorAccent">
</ripple>
复制代码
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/itemBackground">
<item >
<color android:color="@android:color/white" />
</item>
</ripple>
复制代码
对比后,发现绿色的文字部分通过了二重绘制,由于布局的白色背景和文字自身颜色的缘由。若是布局背景能去掉还能实现水波纹的效果就行了,这样就只有文字一层的颜色。android
一、使用系统自带有界水波纹实现方式,由于系统自己的默认背景是透明色的。less
android:background="?android:attr/selectableItemBackground"
复制代码
系统的默认水波纹颜色是灰色,若是须要使用对应的高亮色来做为ripple的背景色,咱们能够在
styles-v21
系统主题里加入这个:<item name = "android:colorControlHighlight">@color/colorAccent</item>
布局
二、使用自定义有界水波纹效果,使其默认背景色为透明色。 写法:spa
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/itemBackground">
<item android:id="@android:id/mask">
<color android:color="@android:color/white" />
</item>
</ripple>
复制代码
添item时,若是指定id为@android:id/mask,那么不点击时不会显示出该item指定的color。 能够设置指定子层item的android:id="@android:id/mask"来设定当前Ripple的Mask。 Mask的内容并不会被绘制到屏幕上,它的做用是限定Ripple效果的绘制区域。.net
最后能够获得咱们想要的效果: 调试
在使用小红书时,咱们能够看到关于“笔记”的item长按会展现扩散的效果。code
android:foreground="?attr/selectableItemBackgroundBorderless"
复制代码
又或者,无边界的水波纹也能够达到长按扩散的效果,只是它会超出边界,那咱们就在对应的父布局加一层有边界的水波纹背景便可。就像这样:cdn
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:onClick="@{()->adapter.openDetail(bean)}"
android:padding="8dp">
</RelativeLayout>
</RelativeLayout>
复制代码
二者的区别是:长按扩散时,前者的水波纹会在图片之上,然后者在图片之下。
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:onClick="login"
android:text="登录"
android:textColor="@android:color/white"
android:textStyle="bold" />
复制代码
The Widget.AppCompat.Button.Colored 继承了 Widget.AppCompat.Button style而且根据你选择的主题应用最接近的颜色。