I am using the RecyclerView
in my application and for the needs of my design, I need to have different margins between the items in my list (For example: the space between the first two items to be 16dp, the space between the second and the third item 32dp etc.). I read that you can add item decoration to the RecyclerView
and create that space between the items. But this thing adds the same margin between all the items, and I want different behavior for different items. My questions is, can this be done using the item decoration? And how is this approach better than changing the margin of the item (view) in for example, the onBindViewHolder
method in the RecyclerView.Adapter
. Thank you in advance!
We have to create a default Divider using addItemDecoration() method with the RecyclerView instance, we need to pass the ItemDecoration(in this case it is DividerItemDecoration()) instance and the orientation of the LayoutManager(in this case it is vertical) of the recycler view.
An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.
You can override RecyclerView.ItemDecoration#getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
, it is called for every visible child View view
, you can get its position within the adapter by calling:
parent.getChildAdapterPosition(view)
or the view holder by calling:
parent.getChildViewHolder(view)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With