RecyclerView.ViewHolder - getLayoutPosition vs getAdapterPosition

前端 未结 2 1209
生来不讨喜
生来不讨喜 2020-12-12 10:23

Since the new support library version (22.x) the getPosition() method of the RecyclerView.ViewHolder class has been deprecated in lieu of the metho

2条回答
  •  囚心锁ツ
    2020-12-12 10:44



    In order to argue the difference(s) of getAdapterPosition(), getLayoutPosition(), and also position; we would notice the cases below:

    1.position argument in onBindViewHolder() method:

    We can use the position to bind data to the view and it is okay to use position argument to do this, but it is not okay to use position argument to handle user clicks and if you used it you will see a warning tells you "not to treat position as fixed and use holder.getAdapterPosition() instead".

    2.getAdapterPosition():

    This method always consists the updated adapter’s position of the holder. It means whenever you clicked on an item, you ask the adapter about it’s position. so you will get the latest position of this item in terms of Adapter’s logic.

    3.getLayoutPosition():

    Sometimes, it is needed to find the position in terms of the updated layout (the last passed layout that the user is seeing now), for example: If the user asks for the third position he can see and you use swipe/dismiss for items or apply any animation or decorations for items it will be better to use getLayoutPosition() instead of getAdapterPosition(), cause you will always be sure that you are dealing with the items’ position in terms of the latest passed layout.


    For more information on this; see here . . .

提交回复
热议问题