android: Android水波纹点击效果

Android API 21及以上新增了ripple标签用来实现水波纹的效果。我们可以通过设置ripple背景来实现一些View点击效果。

该水波纹效果有两种:一种是有界的(点击后类似于一个矩形向四周扩展),一种是无界的(点击后类似于一个圆形向四周扩展)。

系统上的实现效果如下:

有界效果:
在API 21以上使用,才有波纹效果;API 21以下使用只有变色效果,没有波纹效果。

android:background="?android:attr/selectableItemBackground"

无界效果:
在API 21以上才能使用,API 21以下会报错无法编译,最小版本要设置为minSdkVersion 21

android:background="?android:attr/selectableItemBackgroundBorderless"

由于在API 21以下无法使用ripple 标签来实现波纹效果,为了兼容低版本机型不出错,我们需要做波纹效果适配。

可以在res目录下新建一个drawable-v21的文件夹,然后在其中新建一个名为bg_ripple的文件:

<?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就是按下的水波纹颜色。

然后在drawable文件夹下也新建一个名为bg_ripple的文件:

<?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>

在布局中使用:

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_ripple"/>

参考链接:

1. Android水波纹点击效果

Android水波纹点击效果

 
原文地址:https://www.cnblogs.com/yongdaimi/p/11732034.html