Android 控件实现波纹效果

实现波纹效果两种方式

一.通过设置控件theme和background(foreground)属性

1.定义style

   <style name="Ripple">
        <item name="android:colorControlHighlight">#D8D8D8</item> <!-- 指定点击时波纹的颜色-->
        <item name="android:radius">10dp</item> <!-- 这个选项根据需要设置,指定点击时波纹的半径大小-->
    </style>

2.设置涟漪效果
有边界的涟漪效果属性:

?android:attr/selectableItemBackground

无边界的涟漪效果属性

?android:attr/selectableItemBackgroundBorderless

一般在控件的android:background 属性上进行设置即可;如果控件已经使用了android:background属性去设置背景色或者背景图片,但是又想要有点击时的涟漪效果,那么可以考虑在android:foreground属性中设置涟漪效果,这样同样可以达到点击时产生涟漪,也不会影响控件背景的设置。当没有边界时,foreground和background显示效果不一样,foreground波纹效果不会超过控件大小,而background会超过控件大小,但是不会超过其父控件的大小。

3.在控件中设置

 android:theme="@style/Ripple"
 android:background="?android:attr/selectableItemBackgroundBorderless"

如果控件默认不可点击,除Button、ImageButton控件外,如TextView、ImageView等,则需要设置 android:clickable=“true”

例如:

     <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:focusable="true"
                 android:theme="@style/Ripple"
                android:background="?android:attr/selectableItemBackgroundBorderless"
                android:text="Ripple" />

ripple样式和边界涟漪效果属性组合实现不同效果,如下:
在这里插入图片描述

     <style name="RippleNoSize">
        <item name="android:colorControlHighlight">@color/teal_200</item><!-- 指定点击时波纹的颜色-->
    </style>

    <style name="RippleSize">
        <item name="android:colorControlHighlight">@color/teal_200</item><!-- 指定点击时波纹的颜色-->
        <item name="android:radius">10dp</item> <!-- 指定点击时波纹的大小-->
    </style>

其中@color/teal_200值为自定义颜色

二.通过background加载ripple的drawable文件

1.res的drawable目录下定义ripple资源文件,例如:ripple_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#0ADCDD"><!--波纹的颜色 -->
</ripple>

没有设置item,即为无边界的波纹效果

2.在控件中的background引用ripple资源文件

  android:background="@drawable/ripple_bg"

例如:

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/ripple_bg"
        android:gravity="center"
        android:clickable="true"
        android:padding="15dp"
        android:text="rippleStyle无边界无大小" />

如果控件默认不可点击,除Button、ImageButton控件外,如TextView、ImageView等,则需要设置 android:clickable=“true”

在ripple资源文件中,可通过item选项来实现有无边界效果

有边界的ripple

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#0ADCDD">
    <item android:id="@android:id/mask"
        android:drawable="@android:color/white" />
</ripple>

在这里插入图片描述
通过item可设置其他样式,参考Android L Ripple的使用

参考

1.android 控件点击,波纹效果(Ripple的详解)

2.Android L Ripple的使用

猜你喜欢

转载自blog.csdn.net/fengyulinde/article/details/118570652