RecyclerView如何获取行位置并解决get方法无法解析错误
解决RecyclerView行位置获取与「Cannot resolve method 'get(java.lang.String)'」错误
嘿,我来帮你搞定这两个问题:
一、先解决「Cannot resolve method 'get(java.lang.String)'」错误
你代码里的listOfItems是一个String数组,而get()方法是Java中List集合的专属方法,数组并不支持这个方法——要访问数组元素得用下标访问符[]。另外你还犯了个小错误:holder.getLayoutPosition()+" item"的拼接顺序不对,应该先拿到位置值,再和字符串拼接。
修正后的Toast代码可以写成这样:
Toast.makeText(holder.textShow.getContext(), "you pressed the " + listOfItems[holder.getAdapterPosition()] + " item", Toast.LENGTH_SHORT).show();
如果你想直接用onBindViewHolder传入的position参数(这个参数是当前项绑定时刻的适配器位置),也可以这么写:
Toast.makeText(holder.textShow.getContext(), "you pressed the " + listOfItems[position] + " item", Toast.LENGTH_SHORT).show();
二、RecyclerView行位置的正确获取方式
在RecyclerView中,获取行位置有几种常用方式,适用场景略有不同:
- 直接使用
onBindViewHolder的position参数:这是当前项绑定到ViewHolder时的适配器位置,适合静态数据集(不会增删改数据)的场景,用起来最简单。 - 调用
holder.getAdapterPosition():返回当前ViewHolder对应的最新适配器位置,当数据集发生变化(比如添加、删除、移动项)时,这个方法会返回更新后的位置,比直接用position更可靠,推荐在点击事件这类可能延迟触发的场景中使用。 - 调用
holder.getLayoutPosition():返回当前ViewHolder在RecyclerView布局中的显示位置,这个位置和适配器位置可能存在差异(比如RecyclerView执行动画的过程中),一般只有在需要和布局显示相关的操作时才用它。
另外要注意:如果ViewHolder已经被回收,getAdapterPosition()会返回RecyclerView.NO_POSITION,严谨一点可以加个判断:
int currentPos = holder.getAdapterPosition(); if (currentPos != RecyclerView.NO_POSITION) { Toast.makeText(holder.textShow.getContext(), "you pressed the " + listOfItems[currentPos] + " item", Toast.LENGTH_SHORT).show(); }
内容的提问来源于stack exchange,提问作者Abd Al Rahman Al-Mashagbeh
相关产品推荐
相关产品推荐

