简体   繁体   English

如何仅在 RecyclerView 中的某些元素之间添加分隔线?

[英]How do you add dividers between only certain elements in a RecyclerView?

I'm aware of the DividerItemDecoration with regards to RecyclerViews although instead of a divider between every item I'm more interested in a divider whenever a certain attribute changes within my elements.我知道关于 RecyclerViews 的 DividerItemDecoration 虽然不是每个项目之间的分隔线,但每当我的元素中的某个属性发生变化时,我对分隔线更感兴趣。 For example, a list of transactions that hold the date by which they were posted - a divider would then display at each change in date in the list of transactions.例如,一个包含发布日期的交易列表 - 然后在交易列表中的每个日期更改时显示一个分隔符。

This is definitely possible but I'm just not sure to go about doing it.这绝对是可能的,但我不确定是否会去做。 For example, in the Monzo application - it's the dates that separate the transaction lines.例如,在Monzo应用程序中 - 它是分隔交易行的日期。

Any help would be very much appreciated!任何帮助将不胜感激!

You would create a recycler view adapter with two viewholders.您将创建一个带有两个视图支架的回收器视图适配器。 In the example of the Monzo app, you would create one ViewHolder for the purchase and the other for the date.在 Monzo 应用程序的示例中,您将为购买创建一个 ViewHolder,为日期创建另一个。 Then in onCreateViewHolder you would inflate the correct type of viewholder for that item in that list.然后在onCreateViewHolder您将为该列表中的该项目膨胀正确类型的查看器。

One way you could do it is to add the divider to the ViewHolder layout, defaulting to View.INVISIBLE (or View.GONE if you want it to take up extra space when it's visible - like the divider is outside the list element instead of inside at the top edge)您可以这样做的一种方法是将分隔符添加到ViewHolder布局,默认为View.INVISIBLE (或View.GONE如果您希望它在可见时占用额外的空间 - 就像分隔符在列表元素之外而不是在里面在顶部边缘)

Then in onBindViewHolder you could do a bit of logic to decide if the divider should be set to visible or not for that item - something that decides if it represents a date change, and make sure to check it's not the first item in the list too (don't want a random divider up there)然后在onBindViewHolder您可以做一些逻辑来决定该项目的分隔符是否应该设置为可见 - 决定它是否代表日期更改的东西,并确保检查它不是列表中的第一项(不想在那里随机分隔)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM