android – RecyclerView different itemDecoration for different items-ThrowExceptions

Exception or error:

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!

How to solve:

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)

Leave a Reply

Your email address will not be published. Required fields are marked *