美文网首页
RecycleView的position

RecycleView的position

作者: 一个简单搬运工 | 来源:发表于2017-12-07 16:50 被阅读8次

    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.

    相关文章

      网友评论

          本文标题:RecycleView的position

          本文链接:https://www.haomeiwen.com/subject/pqcjixtx.html