在项目中需要实现item的渐变隐藏,一开始想复杂了,兜兜转转一圈才发现可以用最简单的方式实现。
效果如下:
需要源码的同学,转到github下载
一、方式
1.基本思路
这种简单的渐变隐藏效果,可以使用蒙层的思路去完成。也就是如图,我们可以在RecyclerView上添加一个透明度渐变的图层,这样随着透明度的减少,RecyclerView就渐变隐藏了。
2.蒙层的建立
透明渐变的图层需要用到LayerDrawable
和ShapeDrawable
,对应标签是<layer-list>
和<shape>
,通过在res/drawable文件夹下建立.xml文件进行定义。
<layer-list>
通过设置item来进行不同drawable复合,而<shape>
中的<gradient>
用于设置渐变,<solid>
用于设置纯色。
3.颜色数值的解析
在#FFFFFF
这种六位颜色数值的表示中,前两位代表透明度,后四位才代表具体的颜色。前两位为#FF
代表完全不透明,#00
代表完全透明。
比如淡紫色为#E6E6FA
,是示例的背景色,那么蒙层只需要从#00E6E6FA
到#FFE6E6FA
就可以实现透明到不透明的渐变。
二、代码解析
省略RecyclerView的创建代码,直接看布局文件。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
....
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:background="@color/colorbackground"
android:id="@+id/recycleview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/layer_list_mask"/>
</android.support.constraint.ConstraintLayout>
很简单的布局,我们只是在RecyclerView上,添加了一个同等大小的ImageView作为蒙层。
我们来看蒙层的代码,也就是上面的@drawble/layer_list_mask.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--透明渐变蒙层-->
<item
android:bottom="100dp"
android:top="350dp">
<shape android:shape="rectangle">
<!--设置渐变-->
<gradient
android:angle="-90"
android:startColor="#00E6E6FA"
android:endColor="#FFE6E6FA"/>
</shape>
</item>
<!--底部蒙层非透明-->
<item
android:height="100dp"
android:gravity="bottom">
<shape android:shape="rectangle">
<!--设置纯颜色进行遮挡-->
<solid android:color="#FFE6E6FA" />
</shape>
</item>
</layer-list>
笔者用<layer-list>
标签让两个shape复合,而逐渐不透明的渐变 从顶部350dp开始,距离底部100dp的地方结束。最后,底部的100dp部分用纯色,就会遮挡住这一部分了。
你可以调整或者按着自己的思路来建立蒙层,达到期望的效果。
希望这篇文章可以有所帮助。