怎么在Android中利用Item实现一个点击水波纹效果

怎么在Android中利用Item实现一个点击水波纹效果?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

Android是什么

Android是一种基于Linux内核的*及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。

系统自带的水波纹实现

系统自带的方法非常方便,只需要给相应的空间设置背景,背景内容则为系统自带的 selectableItemBackground ,这样的话,水波纹就会在TextView所在的区域内进行绘制。

<TextView
android:background="?android:attr/selectableItemBackground"
... />

ripple的使用(需要V21以上)

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
 android:color="@color/dark_blue">
 <item android:drawable="@color/blue"/>
</ripple>

其中item的颜色是控件正常状态的背景色,ripple中的颜色是点击时出现的颜色(会以半透明的形式展示出来)。ripple颜色的变化效果要比selector的效果更加柔和,以渐变的形式出现。

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
 android:color="@color/dark_blue">
 <item android:id="@android:id/mask" android:drawable="@drawable/ic_launcher_foreground"/>
</ripple>

mask的作用:只能在规定范围内显示水波动画,范围边界由mask遮罩对象指定(可以换一些比原有背景小的图片资源,可以看出效果)。

将ripple文件设置为控件的背景色就可以了。对于没有设置点击事件的控件,是没有变化效果的。需要为控件设置 android:clickable="true"

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/main_item_tv"
 android:layout_width="match_parent"
 android:layout_height="50dp"
 android:clickable="true"
 android:background="@drawable/item_blue_selector"
 android:gravity="center"
 android:textSize="17sp" />

对于低版本来说,我还是选择selector作为适配方案。截止到现在,21及以上版本已经覆盖了90%的设备。

foreground设置

现在的点击水波纹效果只有在抬起手指的时候才能看到,不符合一些项目的需求。

其实在控件除了设置background,还可以设置foreground。

android:foreground="?attr/selectableItemBackgroundBorderless"

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。