Android水波纹点击效果

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

《Android水波纹点击效果》 水波纹样图

1. 水波纹效果实现

1)系统效果

  • 系统有界效果
    在API 21以上使用,才有波纹效果;API 21以下使用只有变色效果,没有波纹效果
android:background="?android:attr/selectableItemBackground"
  • 系统无界效果
    在API 21以上才能使用,API 21以下会报错无法编译,最小版本要设置为minSdkVersion 21
android:background="?android:attr/selectableItemBackgroundBorderless"

2)自定义效果
res中新建一个drawable-v21文件夹,在此文件夹下新建ripple_bg.xml用于实现波纹效果。(仅限Android 5.0以上机型)

  • 自定义有界效果
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/gray"> <!--波纹颜色-->
      <item>
        <shape android:shape="rectangle">
            <!-- 填充背景色-->
            <solid android:color="@color/white"/>
        </shape>
    </item>
</ripple>
  • 自定义无界效果
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/gray"> <!--波纹颜色-->   
</ripple>
  • 自定义带图片效果
<?xml version="1.0" encoding="utf-8"?>  
<ripple xmlns:android="http://schemas.android.com/apk/res/android" 
        android:color="@color/gray">    <!--波纹颜色-->   
   <item>
        <selector>
             <!-- 未点击背景图-->
            <item
                android:drawable="@drawable/normal_bg"
                android:state_pressed="false" />
             <!-- 点击背景图-->
            <item
                android:drawable="@drawable/select_bg"
                android:state_pressed="true" />
        </selector>
    </item>
</ripple>

在布局中使用:

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_bg"/>
2. 水波纹效果兼容

在API 21以下无法使用ripple标签来实现波纹效果,为了兼容低版本机型不出错,我们需要做波纹效果适配。
1)系统效果(只有变色效果,没有波纹效果)

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

2)自定义效果(只有变色效果,没有波纹效果)
drawable文件下创建同名文件ripple_bg.xml用于适配Android 5.0以下机型。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- 单击时的背景颜色 -->
    <item
        android:drawable="@color/gray"
        android:state_pressed="true">
    </item>
  <!-- 未单击时的背景颜色 -->
    <item
        android:drawable="@color/white"
        android:state_pressed="false">
    </item>
</selector>

在布局中使用:

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_bg"/>
    原文作者:翻译不了的声响
    原文地址: https://www.jianshu.com/p/b8101b96246a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞