RecyclerView仅在某些项目之间添加分隔线 [英] RecyclerView add divider lines only between some items

查看:78
本文介绍了RecyclerView仅在某些项目之间添加分隔线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的RecyclerView Layout中添加分隔线.我已经搜索了一段时间,但是我只能找到利用RecyclerView.addItemDecoration的解决方案,该解决方案在所有项目之间添加了分隔符.我可以创建一个只有一行的布局,然后将其添加到RecyclerView,但这对我来说似乎不是一个优雅的解决方案.

I want to add divider lines in my RecyclerView Layout. I already searched some time, but I can only find solutions that utilise RecyclerView.addItemDecoration, which adds the divider between all items. I could create a layout that has a single line and add that to the RecyclerView, but that doesn't seem like an elegant solution to me.

推荐答案

您可以编写自定义RecyclerView.ItemDecoration并仅在需要的地方绘制分隔线.并将其设置为RecyclerView使用:

You can write a custom RecyclerView.ItemDecoration and draw divider only where you need. And set it to RecyclerView using:

recyclerView.addItemDecoration(new YourItemDecoration());

这是默认的DividerItemDecoration源代码:

This is the default DividerItemDecoration source code: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/android/support/v7/widget/DividerItemDecoration.java

您可以在onDraw方法中找到分隔线绘制逻辑,在该逻辑中为所有项目绘制分隔线.您只需要根据需要为某些项目绘制分隔线来更改该部分. getItemOffsets()方法为项目增加偏移量,以为分隔符腾出空间.

You can find the divider drawing logic in onDraw method, where it draws divider for all items. You have to change that part based on your needs to draw divider for some items only. getItemOffsets() method adds offset to the item to make space for the divider.

这篇关于RecyclerView仅在某些项目之间添加分隔线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆