简体   繁体   中英

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. 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.

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. Then in onCreateViewHolder you would inflate the correct type of viewholder for that item in that list.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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