RecyclerView利用ItemDecoration实现头部悬停效果【类似微信通讯录效果】

本文主要是介绍RecyclerView利用ItemDecoration实现头部悬停效果【类似微信通讯录效果】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

对于RecyclerView的ItemDecoration相信大家都不会陌生,因为RecyclerView并不像ListView那样自带分割线,所以我们需要继承ItemDecoration去手动绘制分割线。本篇文章主要是利用ItemDecoration的特性来绘制实现悬浮效果,就像微信中的通讯录一样,只不过微信的通讯录没有悬停而已。

没有效果图,光bb是不具有说服力的,下面我们来看下效果图
这里写图片描述

ItemDecoration中的几个关键方法介绍

(1)getItemOffsets()

(2)onDraw()

(3)onDrawOver()

说明:在解释上面的几个重要的方法之前,我们先来看一张图
这里写图片描述
这里非常感谢Piasy大牛提供的图片,原文地址:https://blog.piasy.com/2016/03/26/Insight-Android-RecyclerView-ItemDecoration/?utm_source=tuicool&utm_medium=referral

由上面的效果图可以看出来,通过设置RecyclerView的item的不同方向的padding值,可以让我们的item空出不同方向的距离,我们就可以利用空出的距离来绘制我们的悬浮栏了。为什么说是padding值呢?我们大体说一下,查看官方DividerItemDecoration源码,不能翻墙了,借用上图作者文章中的一段代码

@Overridepublic void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {if (mOrientation == VERTICAL_LIST) {outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());} else {outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);}}

我们看到了,以其中一种情况分析,当我们的item是垂直排列的时候,outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());下方空出来的是mDivider.getIntrinsicHeight()高度的距离。在RecyclerView源代码中找到调用getItemOffsets()的方法,即:getItemDecorInsetsForChild(View child)方法

Rect getItemDecorInsetsForChild(View child) {final LayoutParams lp = (LayoutParams) child.getLayoutParams();if (!lp.mInsetsDirty) {return lp.mDecorInsets;}if (mState.isPreLayout() && (lp.isItemChanged() || lp.isViewInvalid())) {// changed/invalid items should not be updated until they are rebound.return lp.mDecorInsets;}final Rect insets = lp.mDecorInsets;insets.set(0, 0, 0, 0);final int decorCount = mItemDecorations.size();for (int i = 0; i < decorCount; i++) {mTempRect.set(0, 0, 0, 0);mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);insets.left += mTempRect.left;insets.top += mTempRect.top;insets.right += mTempRect.right;insets.bottom += mTempRect.bottom;}lp.mInsetsDirty = false;return insets;}

我们看到,outRect.set(left, top, right, bottom)的值放到了Rect对象的insets 变量中,然后我们再继续查找这个insets,如何查找,我们需要看看谁调用了 getItemDecorInsetsForChild(View child) 方法。在RecyclerView源码中继续搜索,定位到measureChild(View child, int widthUsed, int heightUsed)方法

/*** Measure a child view using standard measurement policy, taking the padding* of the parent RecyclerView and any added item decorations into account.** <p>If the RecyclerView can be scrolled in either dimension the caller may* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>** @param child Child view to measure* @param widthUsed Width in pixels currently consumed by other views, if relevant* @param heightUsed Height in pixels currently consumed by other views, if relevant*/public void measureChild(View child, int widthUsed, int heightUsed) {final LayoutParams lp = (LayoutParams) child.getLayoutParams();final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);widthUsed += insets.left + insets.right;heightUsed += insets.top + insets.bottom;final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,canScrollHorizontally());final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,canScrollVertically());if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {child.measure(widthSpec, heightSpec);}}

现在就清晰了,在测量子item的宽高时,原来存到insets中的left、right、top、bottom分别加到了对应的padding值中去了,getChildMeasureSpec(getWidth(), getWidthMode(),getPaddingLeft() +getPaddingRight() + widthUsed, lp.width,canScrollHorizontally());

说了这么多就是为了分析getItemOffsets()方法的作用,就是通过设置RecyclerView的item的上下左右padding值,来预留出空间,通过上面的图片加之源码的分析,我们理解起来就更加容易了。

既然已经预留了item的paddingTop的距离了,那么我们就需要用到第二个方法onDraw()去绘制我们要显示的内容。由效果图可以看出我们要绘制的就是一个矩形条以及文字,所以接下来的工作就又回归到我们熟悉的自定义view上面了。首先我们要先new出来画笔,getItemOffsets()方法中具体该预留多高的空间?其实就是矩形条的高度,分析完了,接下来看这两个方法中的代码逻辑

@Overridepublic void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {super.getItemOffsets(outRect, view, parent, state);//通过查看源码可知道获取position的方法int position = ((RecyclerView.LayoutParams)view.getLayoutParams()).getViewLayoutPosition();if(position > -1){if(position == 0){//默认第一个位置,肯定是要设置悬浮栏的,这里只需要上边top留出空间即可outRect.set(0, titleHeight, 0, 0);//里面参数表示:左上右下的内边距padding距离}else{//继续分情况判断,当滑动到某一个item时(position位置)得到tag标签,与上一个item对应的标签不一致( position-1 位置),说明这是下一分组了if(lists.get(position).getTag() != null && !lists.get(position).getTag().equals(lists.get(position-1).getTag())){//说明这是下一组了,需要留出空间好去绘制悬浮栏用outRect.set(0, titleHeight, 0, 0);}else{//标签相同说明是同一组的数据,比如都是 A 组下面的数据,那么就不需要再留出空间绘制悬浮栏了,共用同一个 A 组即可outRect.set(0, 0, 0, 0);}}}}

说明一点:我们该通过具体哪种方法获得position相应的位置呢?不知道的话就可以点进去查看源代码中是如何处理的

public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),parent);}其中:
/*** Returns the adapter position that the view this LayoutParams is attached to corresponds* to as of latest layout calculation.** @return the adapter position this view as of latest layout pass*/public int getViewLayoutPosition() {return mViewHolder.getLayoutPosition();}

接着,我们继续看我们的onDraw()方法

@Overridepublic void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {super.onDraw(c, parent, state);//先画出带有背景颜色的矩形条悬浮栏,从哪个位置开始绘制到哪个位置结束,则需要先确定位置,再画文字(即:title)int left = parent.getPaddingLeft();int right = parent.getWidth() - parent.getPaddingRight();//父view(RecyclerView)有padding值,子view有margin值int childCount = parent.getChildCount();//得到的数据其实是一屏可见的item数量并非总item数,再复用for(int i = 0; i < childCount; i++){View child = parent.getChildAt(i);//子view(即:item)有可能设置有margin值,所以需要parms来设置margin值。 RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();//以及 获取 position 位置int position = params.getViewLayoutPosition();if(position > -1){if(position == 0){//肯定是要绘制一个悬浮栏 以及 悬浮栏内的文字//画矩形悬浮条以及文字drawRectAndText(c, left, right, child, params, position);}else{if(lists.get(position).getTag() != null && !lists.get(position).getTag().equals(lists.get(position - 1).getTag())){//和上一个Tag不一样,说明是另一个新的分组//画矩形悬浮条以及文字drawRectAndText(c, left, right, child, params, position);}else{//说明是一组的,什么也不画,共用同一个Tag}}}}}

这样,我们就实现了简单的微信中的通讯录效果,在调试过程中,我们可以发现:当我们在getItemOffsets()方法中通过outRect.set(0, titleHeight, 0, 0)为我们的onDraw()中绘制矩形条预留空间,假如我们预留的空间小于我们要绘制的实际高度时,也就是说我们在getItemOffsets()方法中预留了20dp的paddingTop距离,而我们实际在onDraw()中绘制的矩形高度时30dp,那么又将出现什么现象呢?先看效果图

这里写图片描述

我们看到绘制的灰色的矩形条超出getItemOffsets()为我们预留的空间时,就会被item遮盖,但是会有残影,如上图所示。有童鞋该说了,为什么顶部的A矩形条没有,那是因为我重写了另一个方法,也就是我们接下啦要介绍的onDrawOver()方法。出现这个的原因是因为ItemDecoration的onDraw()方法比View(RecyclerView)的onDraw()先执行,也就是说,ItemDecoration的onDraw()绘制的内容处于最底层。ItemDecoration的onDraw()方法为什么会先于View的onDraw()方法执行?我们可以查看源代码,由于篇幅原因,这里就不再分析了。

接下来,我们分析最后一个方法:onDrawOver()方法

从上面分析被遮盖的图片中,我们看到为什么A所在的矩形条没有没item遮盖住呢?因为我们在onDrawOver()方法中绘制了一个靠顶的矩形条,onDrawOver()方法自带悬浮特性。也就是说,这里的A所在的矩形条是在item的上层的。从而可以看出onDrawOver()方法是最后才执行的(当然了,执行的顺序还是需要查看源代码的!!!),简单说下这几个执行的顺序:getItemOffsets()方法—>ItemDecoration的onDraw()方法—>View的onDraw()方法绘制item的view—>ItemDecoration的onDrawOver()方法。

@Overridepublic void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {super.onDrawOver(c, parent, state);//其实就是获取到每一个可见的位置的item时,执行画顶层悬浮栏int firstPosition = ((LinearLayoutManager)parent.getLayoutManager()).findFirstVisibleItemPosition();//    View child = parent.getChildAt(firstPosition);View child = parent.findViewHolderForLayoutPosition(firstPosition).itemView;//绘制悬浮栏,其实这里和上面onDraw()绘制方法差不多,只不过,这里面的绘制是在最上层,会悬浮paint.setColor(Color.parseColor("#FFDFDFDF"));c.drawRect(parent.getPaddingLeft(), parent.getPaddingTop(), parent.getRight() - parent.getPaddingRight(), parent.getPaddingTop() + titleHeight, paint);//绘制文字paint.setColor(Color.parseColor("#88888888"));paint.getTextBounds(lists.get(firstPosition).getTag(), 0, lists.get(firstPosition).getTag().length(), rectBounds);c.drawText(lists.get(firstPosition).getTag(), child.getPaddingLeft(), parent.getPaddingTop() + titleHeight - (titleHeight/2 - rectBounds.height()/2), paint);}
上述代码中,我们可以看到item是不是需要预留空间,需要根据tag标记来决定。这个tag标记是我们定义在实体类中的一个字段,作用就是为了根据此标记将具有同一此标记的数据分到同一组中。

接下来看下我们的实体类

/***  实体类*/public class CategoryBean implements Serializable{private static final long serialVersionUID = 5136218664701666396L;private String tag;//所属的分类private String categoryName;public CategoryBean(String tag, String categoryName) {this.tag = tag;this.categoryName = categoryName;}public String getTag() {return tag;}public void setTag(String tag) {this.tag = tag;}public String getCategoryName() {return categoryName;}public void setCategoryName(String categoryName) {this.categoryName = categoryName;}
}

adapter适配器

/***  适配器*/public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder>{private Context context;private List<CategoryBean> lists;private LayoutInflater inflater;public CategoryAdapter(Context context, List<CategoryBean> lists) {this.context = context;this.lists = lists;inflater = LayoutInflater.from(context);}@Overridepublic CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {View view = inflater.inflate(R.layout.item_category, parent, false);CategoryViewHolder holder = new CategoryViewHolder(view);return holder;}@Overridepublic void onBindViewHolder(CategoryViewHolder holder, final int position) {CategoryBean bean = lists.get(position);holder.tvName.setText(bean.getCategoryName());holder.itemView.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(context, "点击了的位置position= "+ position, Toast.LENGTH_SHORT).show();}});}@Overridepublic int getItemCount() {return null !=lists ?lists.size() : 0;}public static class CategoryViewHolder extends RecyclerView.ViewHolder{TextView tvName;public CategoryViewHolder(View itemView) {super(itemView);tvName = (TextView) itemView.findViewById(R.id.tvName);}}
}

最后,我们看看如何去使用

public class MainActivity extends AppCompatActivity {private TitleItemDecoration titleItemDecoration;private RecyclerView recyclerView;private CategoryAdapter adapter;private List<CategoryBean> lists;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);recyclerView = (RecyclerView) findViewById(R.id.recyclerView);recyclerView.setLayoutManager(new LinearLayoutManager(this));//设置测试数据setDatas();adapter = new CategoryAdapter(this, lists);recyclerView.setAdapter(adapter);titleItemDecoration = new TitleItemDecoration(this, lists);recyclerView.addItemDecoration(titleItemDecoration);}private void setDatas() {lists = new ArrayList<>();lists.add(new CategoryBean("A", "哎"));lists.add(new CategoryBean("A", "爱"));lists.add(new CategoryBean("A", "昂"));lists.add(new CategoryBean("B", "beautiful"));lists.add(new CategoryBean("B", "beak"));lists.add(new CategoryBean("B", "but"));lists.add(new CategoryBean("B", "bring"));lists.add(new CategoryBean("C", "category"));lists.add(new CategoryBean("C", "can"));lists.add(new CategoryBean("C", "captive"));lists.add(new CategoryBean("C", "computer"));lists.add(new CategoryBean("D", "default"));}
}
参考的牛人博客链接
张旭童 http://blog.csdn.net/zxt0601
Piasy https://blog.piasy.com/2016/03/26/Insight-Android-RecyclerView-ItemDecoration/?utm_source=tuicool&utm_medium=referral
站在牛人的肩膀上,我们将会更加轻松。非常感谢那些无私奉献的大牛们。当我们遇到一些解决不了或者没思路的问题时,要学会翻阅源码,或者官方的一些示例代码,会有意外的惊喜。最后不得不说,RecyclerView中相关的内容很多很强大。
希望能对你有所帮助,主要代码已经贴出来了,下班咯,源代码就不再上传了,如果有需要源码的请跟我说下
点击下载源码

这篇关于RecyclerView利用ItemDecoration实现头部悬停效果【类似微信通讯录效果】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/155027

相关文章

W外链微信推广短连接怎么做?

制作微信推广链接的难点分析 一、内容创作难度 制作微信推广链接时,首先需要创作有吸引力的内容。这不仅要求内容本身有趣、有价值,还要能够激起人们的分享欲望。对于许多企业和个人来说,尤其是那些缺乏创意和写作能力的人来说,这是制作微信推广链接的一大难点。 二、精准定位难度 微信用户群体庞大,不同用户的需求和兴趣各异。因此,制作推广链接时需要精准定位目标受众,以便更有效地吸引他们点击并分享链接

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

防近视护眼台灯什么牌子好?五款防近视效果好的护眼台灯推荐

在家里,灯具是属于离不开的家具,每个大大小小的地方都需要的照亮,所以一盏好灯是必不可少的,每个发挥着作用。而护眼台灯就起了一个保护眼睛,预防近视的作用。可以保护我们在学习,阅读的时候提供一个合适的光线环境,保护我们的眼睛。防近视护眼台灯什么牌子好?那我们怎么选择一个优秀的护眼台灯也是很重要,才能起到最大的护眼效果。下面五款防近视效果好的护眼台灯推荐: 一:六个推荐防近视效果好的护眼台灯的

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、