加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – onBindViewHolder()中的constructor.getAdapterPosition

发布时间:2020-12-15 04:35:42 所属栏目:Java 来源:网络整理
导读:参见英文答案 Lint error “Do not treat position as fixed; only use immediately…”????????????????????????????????????1个 这是我的代码 – public void onBindViewHolder(myViewHolder holder,int position) { //1. details obj = list.get(holder.g
参见英文答案 > Lint error “Do not treat position as fixed; only use immediately…”????????????????????????????????????1个
这是我的代码 –

public void onBindViewHolder(myViewHolder holder,int position) {

        //1. details obj = list.get(holder.getAdapterPosition());
        //2. details obj = list.get(position);

        holder.position = position;
    }

我收到了警告

Do not treat position as fixed; only use immediately and call
holder.getAdapterPosition() to look it up later RecyclerView will not
call onBindViewHolder again when 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 later.

所以我对1和2感到困惑,我应该选择哪个?为什么?正如它说getAdapterPosition()提供更新的位置,我从列表中获取基于位置的值.

谢谢.

解决方法

你得到的警告不是关于使用position或getAdapterPosition().这是关于保存位置:

holder.position = position;

您不需要在持有者中保存头寸,因为它的位置可以改变,您可以通过调用holder.getAdapterPosition();

来自文档:

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.

关于使用哪个:

如果在onBindViewHolder方法中调用,则两者都应返回相同的结果.我建议使用位置,因为它是最简单和最安全的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读