Lint error “Do not treat position as fixed; only use immediately…”

元气小坏坏 提交于 2019-11-27 15:04:15

The documentation of RecyclerView.Adapter.onBindViewHolder() states:

Note that unlike ListView, RecyclerView will not call this method again if the position of the item changes in the data set unless the item itself is invalidated or the new position cannot be determined. For this reason, you should only use the position parameter while acquiring the related data item inside this method and should not keep a copy of it. If you need the position of an item later on (e.g. in a click listener), use getAdapterPosition() which will have the updated adapter position

So, technically items may be re-arranged and binding will not be necessary because items are not invalidated yet. The position variable received holds true only for the scope of bind function and will not always point to correct position in the data set. That's why the function getAdapterPosition() must be called everytime updated position is needed.

IMHO, mLastPosition = holder.getAdapterPosition(); is still potentially wrong. Because item may be re-arranged and mLastPosition still points to old position.

About why lint is silent, perhaps Lint rule is not that thorough. Its only checking whether position parameter is being copied or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!