android 按钮点按波纹效果

110 阅读1分钟

一般情况下,加入以下属性,即可达到点击波纹效果

 <Button
	  android:foreground="?android:attr/selectableItemBackground"
      />

如果需要波纹效果限制在圆角范围内,可以这么定义 drawable, 然后引用之

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <item>
        <shape
            android:shape="rectangle">
            <corners android:radius="90dp" />
            <solid android:color="@color/global_color"/>
        </shape>
    </item>
</ripple>

在 CardView 中可以这么使用

 <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardBackgroundColor="@{bgColor}"
        app:cardCornerRadius="10dp"
        android:foreground="?android:attr/selectableItemBackgroundBorderless"
        >

再附赠代码的等价操作类

package com.purui.mobile.utils

import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable


object DrawableHelper {

    fun createDrawable(radius:Float, color:Int):Drawable {
        val drawable = GradientDrawable()
        drawable.cornerRadius = radius
        drawable.setColor(color)
        return drawable
    }

    fun createRippleDrawable(radius: Float, color: Int): Drawable {
        val createDrawable = createDrawable(radius, color)

        val stateList = arrayOf(
            intArrayOf(android.R.attr.state_pressed), intArrayOf(android.R.attr.state_focused), intArrayOf(android.R.attr.state_activated),
            intArrayOf()
        )
        // 普通颜色
        val normalColor = ResUtils.getColor(com.purui.mobile.R.color.black_12)
        // 按下颜色
        val pressedColor = ResUtils.getColor(com.purui.mobile.R.color.black_12)
        val stateColorList = intArrayOf(
            pressedColor,
            pressedColor,
            pressedColor,
            normalColor
        )
        return RippleDrawable(ColorStateList(stateList, stateColorList), createDrawable, createDrawable)
    }

    fun createCircleDrawable(size:Int, color:Int):Drawable {
        val drawable = GradientDrawable()
        drawable.shape = GradientDrawable.OVAL
        drawable.setSize(size, size)
        drawable.setColor(color)
        return drawable
    }
}