ItemDecoration overriding getItemOffsets() and animation

Try using the views LayoutParams. If you don't use some custom LayoutManager, it should contain the information you need.

int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewAdapterPosition();

Actually, It's not good decision to get child position from parent. Actual state of view can be different to real state, 'cause at the same time is working or ItemDecorator, or LayoutManager, or RecyclerView to rule them,or Adapter to change position of some elements.

Better way, when ask Recycler to give you ViewHolder for certain view. Then you can get whole information what you need (getLayoutPosition(), getAdapterPosition()).

parent.getChildViewHolder(view).getLayoutPosition();
parent.getChildViewHolder(view).getAdapterPosition;

And another advise, not from your case. If you need to get ItemCount, don’t use adapter.getItemCount(), better is get from state, because count of items can be different in Adapter and Recycler.

state.getItemCount()

I stumbled across this same issue here and I've read the answers and discussions. This maybe a really late answer but I'd answer for the sake of others experiencing this issue.

The answer of Julian Os should have been marked as the correct answer but did not really explained much.

Here's the detailed explaination:

on the ItemDecoration's getItemOffsets() first get the item position parent.getChildViewHolder(view).getAdapterPosition(); as ilyagorbunov has noted this is a safer way of getting the view's position. This method return's RecyclerView.NO_POSITION when the queried view no longer exist. So if that's the case go check for the parent.getChildViewHolder(view).getOldPosition() which returns the old position of an animating view. This method also return's RecyclerView.NO_POSITION when the ChildViewHolder is no longer present in the view or has completed the animation.

If you are having multiple view type in your adapter, just directly get the view type from parent.getChildViewHolder(view).getItemViewType()

For Completeness here's some code snippet:

override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
    super.getItemOffsets(outRect, view, parent, state)
    var position = parent?.getChildViewHolder(view)?.adapterPosition
    if (position == RecyclerView.NO_POSITION) {
        val oldPosition = parent?.getChildViewHolder(view)?.oldPosition
        if (oldPosition == RecyclerView.NO_POSITION) return
        position = oldPosition
    }

    val viewType = parent?.getChildViewHolder(view)?.itemViewType

    when (viewType) {
        //do your outRect here
    }
}