RecyclerView仅在某些项目之间添加分隔线 [英] RecyclerView add divider lines only between some items
问题描述
我想在我的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屋!