Android API 21及以上新增了ripple
标签用来实现水波纹的效果。咱们能够经过设置ripple
背景来实现一些View点击效果。android
该水波纹效果有两种:一种是有界的(点击后相似于一个矩形向四周扩展),一种是无界的(点击后相似于一个圆形向四周扩展)。app
系统上的实现效果以下:less
有界效果:
在API 21以上使用,才有波纹效果;API 21如下使用只有变色效果,没有波纹效果。布局
android:background="?android:attr/selectableItemBackground"
无界效果:
在API 21以上才能使用,API 21如下会报错没法编译,最小版本要设置为minSdkVersion 21
spa
android:background="?android:attr/selectableItemBackgroundBorderless"
因为在API 21如下没法使用ripple 标签来实现波纹效果,为了兼容低版本机型不出错,咱们须要作波纹效果适配。code
能够在res目录下新建一个drawable-v21的文件夹,而后在其中新建一个名为bg_ripple的文件:xml
<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@android:color/darker_gray"> <!--波纹颜色--> </ripple>
这里ripple中的color就是按下的水波纹颜色。blog
而后在drawable文件夹下也新建一个名为bg_ripple的文件:ip
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/colorAccent" android:state_pressed="true" /> <item android:drawable="@android:color/transparent" /> </selector>
在布局中使用:utf-8
<TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_ripple"/>
参考连接: