RecyclerView add divider lines only between some items

Viewed 9666

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.

5 Answers

One way is to create a custom ItemDecoration class

// from Bhuvanesh BS - https://stackoverflow.com/questions/46215810/recyclerview-remove-divider-decorator-after-the-last-item
class DividerItemDecorator(private val divider: Drawable?, private val viewIds: IntArray? = null, private val notViewIds: IntArray? = null) : ItemDecoration() {
    override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val dividerLeft = parent.paddingLeft
        val dividerRight = parent.width - parent.paddingRight
        val childCount = parent.childCount
        for (i in 0 until childCount - 1) {
            val child: View = parent.getChildAt(i)
            if (hasDivider(child.id)) {
                divider?.also {
                    val params = child.layoutParams as RecyclerView.LayoutParams
                    val dividerTop: Int = child.bottom + params.bottomMargin
                    val dividerBottom = dividerTop + it.intrinsicHeight
                    it.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom)
                    it.draw(canvas)
                }
            }
        }
    }
    
    private fun hasDivider(viewId: Int): Boolean {
        return when (viewIds != null) {
            true -> viewIds.contains(viewId)
            false -> {
                when (notViewIds != null) {
                    true -> !notViewIds.contains(viewId)
                    false -> true
                }
            }
        }
    }
}

then pass it the view ids of the items that have a divider

recyclerView.addItemDecoration(DividerItemDecorator(ContextCompat.getDrawable(requireContext(), R.drawable.item_divider), viewIds = intArrayOf(R.id.root_view_id_1, R.id.root_view_id_2)))

or the ids that don't have a divider

recyclerView.addItemDecoration(DividerItemDecorator(ContextCompat.getDrawable(requireContext(), R.drawable.item_divider), notViewIds = intArrayOf(R.id.root_view_id_1, R.id.root_view_id_2)))
Related