RecycleView的position

This is a tricky situation, sorry that docs are not sufficient.

Whenadaptercontents change (and you callnotify***()) RecyclerView requests a newlayout. From that moment, untillayoutsystem decides to calculate a newlayout(<16 ms), thelayoutpositionandadapterpositionmay not match becauselayouthas not reflectedadapterchanges yet.

In your use case, since your data is related to youradaptercontents (and I assume that data is changed at the same time withadapterchanges), you should be usingadapterPosition.

Be careful though, if you are callingnotifyDataSetChanged(), because it invalidates everything, RecyclerView does not know that ViewHolder'sadapterpositionuntil nextlayoutis calculated. In that case,getAdapterPosition()will returnRecyclerView#NO_POSITION(-1).

But lets say if you've callednotifyItemInserted(0), thegetAdapterPosition()of ViewHolder which was previously atposition0will start returning1immediately. So as long as you are dispatching granular notify events, you are always in good state (we knowadapterpositioneven though newlayoutis not calculated yet).

Another example, if you are doing something on user click, ifgetAdapterPosition()returnsNO_POSITION, it is best to ignore that click because you don't know what user clicked (unless you have some other mechanism, e.g. stable ids to lookup the item).

Edit For WhenLayoutPositionis Good

Lets say you are usingLinearLayoutManagerand want to access the ViewHolder above the currently clicked item. In that case, you should uselayoutpositionto get the item above.

mRecyclerView.findViewHolderForLayoutPosition(myViewHolder.getLayoutPosition() - 1)

You have to uselayoutpositionbecause it matches what user is currently seeing on the screen.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,490评论 0 23
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 12,872评论 0 6
  • 1. People come in all shapes and sizes .They also come wi...
    应数二班田玉峰阅读 1,846评论 0 1
  • A小姐在公司被人摸手摸脚,M先生听到后一直不说话,面无表情的看着前方。 A小姐以为M先生不在乎她,有点生气凑到M先...
    Asm小姐阅读 1,279评论 1 0
  • 我也笑我是个天生的野孩子。 最近,很多朋友都已经结婚了,但是大多数抱怨的就是太难了,太烦了,他居然不洗袜子之类的,...
    Hannah_Mon阅读 3,783评论 0 0

友情链接更多精彩内容