I've updated my targetSdkVersion
from 28 to 30 and I've noticed that getAdapterPosition()
is deprecated (I'm not sure when this happened).
In the documentation, they say the following:
This method is deprecated.
This method is confusing when adapters nest other adapters. If you are calling this in the context of an Adapter, you probably want to call getBindingAdapterPosition() or if you want the position as RecyclerView sees it, you should call getAbsoluteAdapterPosition().
The documentation also says the following:
Note that if you are querying the position as RecyclerView sees, you should use getAbsoluteAdapterPosition() (e.g. you want to use it to save scroll state). If you are querying the position to access the RecyclerView.Adapter contents, you should use getBindingAdapterPosition().
How I understand it is:
getBindingAdapterPosition
should be used when you want to get the adapter position (if it still exists in the adapter). If it no longer exists in the adapter, it will return -1
(NO_POSITION).
getAbsoluteAdapterPosition
should be used to get the position as the RecyclerView
sees it. For example, if an item has been deleted, but not yet removed from theViewHolder
.
In other words, if I have 4
items in my Adapter
, I delete position 0
and query getAbsoluteAdapterPosition
and getBindingAdapterPosition
before the item has been removed from the ViewHolder
, then getAbsoluteAdapterPosition
will return 0
(because view is still in the ViewHolder
) and getBindingAdapterPosition
return -1
(Because it no longer exists in the adapter).
I have tested the difference by logging the following:
Log.e("difference", "getAdapterPosition = "+myHolder.getAdapterPosition()+" getBindingAdapterPosition = "+myHolder.getBindingAdapterPosition()+" getAbsoluteAdapterPosition = "+myHolder.getAbsoluteAdapterPosition());
They return exactly the same values. I could not see any difference.
I also see no difference before or after calling notifyItemChanged
, notifyDataSetChanged
or notifyItemRangeChanged
. But when I delete position 0
and call notifyItemRemoved
it returns -1
afterward (for all of them).
My questions
Do I understand this correctly, and when should we be using which? Also, when will there be a difference?
question from:
https://stackoverflow.com/questions/63068519/getadapterposition-is-deprecated 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…