Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView different itemDecoration for different items

Tags:

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!

like image 564
Sandra Avatar asked Dec 09 '14 13:12

Sandra


People also ask

How do I add ItemDecoration to RecyclerView?

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.

What is ItemDecoration RecyclerView?

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.


1 Answers

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) 
like image 141
pskink Avatar answered Sep 28 '22 04:09

pskink