syed_noorullah
syed_noorullah

Reputation: 155

Why does RecyclerView getAdapterPosition() return -1?

I am currently learning android and first time adding swipe to delete functionality to the RecyclerView. I came across the following theory regarding to the swiping functionality but i am unable to understand the reason discussed below as to why getAdapterPosition will return RecyclerView.NO_POSITION.

  • When adapter contents change (and you call notify***) RecyclerView requests a new layout.
  • From that moment, until layout system decides to calculate a new layout (<16 ms), the layout position and adapter position may not match because layout has not reflected adapter changes yet.
  • If you are calling notifyDataSetChanged, it invalidates everything, RecyclerView does not know that ViewHolder's adapter position until next layout is calculated.
  • In that case, getAdapterPosition will return RecyclerView.NO_POSITION (-1)
  • If you've called notifyItemInserted(0), the getAdapterPosition of ViewHolder which was previously at position 0 will start returning 1 immediately.
  • As long as you are dispatching granular notify events, you are always in good state (we know adapter position even though new layout is not calculated yet).

Can someone please explain the above reason and the solution in a simple way.

Upvotes: 0

Views: 582

Answers (1)

cutiko
cutiko

Reputation: 10527

-1 means the scroll could not be computed or the actual position is not valid (in between).

The solution is ignore it

if (getAdapterPosition() == -1) return;

Upvotes: 1

Related Questions