RecyclerView Adapter中如何获取ModelItemsNew列表的条目位置
RecyclerView 加购逻辑索引越界问题修复方案
现存代码的核心问题
- 适配器的渲染基准是
product列表,每个条目的position完全对应product的索引,但代码默认将newitem作为和product等长的平行列表硬索引,最终触发越界——实际传入的newitem长度仅为1,用大于等于1的position取值自然会报错。 - 原有逻辑
holder.amount_value++存在类型错误,TextView是文本控件,无法直接做数值自增运算。 - 点击事件中直接依赖
onBindViewHolder传入的临时position参数,快速滑动、列表增删条目时会出现位置错位,不符合RecyclerView的回收复用机制。
正确的位置获取与逻辑实现
首先需要明确newitem与product的映射关系:两个列表不能默认索引完全对齐,必须通过商品的唯一标识(如商品ID、标题这类不重复字段)做匹配,而非硬拿渲染用的position直接索引newitem。
具体实现步骤:
- 所有点击事件的回调中,统一使用
holder.bindingAdapterPosition获取实时有效位置,这个位置是RecyclerView经过布局校验后的可靠位置,不会因为回收、动画、列表变动出现错位;如果返回RecyclerView.NO_POSITION直接拦截无效操作。 - 绑定条目时,先通过当前商品的唯一标识,匹配
newitem中对应的条目,将条目存储的数量同步到UI。 - 点击加购按钮时,基于实时匹配到的
newitem条目做数量累加,同步更新数据和控件显示,避免ViewHolder复用时出现数量错乱。
核心改动代码示例:
override fun onBindViewHolder(holder: ViewHolder, position: Int) { val products = product[position] holder.title.text = products.title holder.price.text = products.price.toString() Picasso.get().load(products.image).into(holder.imageproduct) // 通过商品唯一标识匹配对应购物车条目,替代硬索引取值 val currentCartItem = newitem.find { it.productId == products.id } // 同步购物车条目的数量到UI holder.amount_value.text = currentCartItem?.itemCount?.toString() ?: "0" holder.itemView.setOnClickListener { // 拦截无效位置 val realPosition = holder.bindingAdapterPosition if (realPosition == RecyclerView.NO_POSITION) return@setOnClickListener val targetProduct = product[realPosition] val bundle = Bundle().apply { putString("title", targetProduct.title) putString("price", targetProduct.price.toString()) putString("image", targetProduct.image.toString()) } val detailFragment = ItemDetailsfragment().apply { arguments = bundle } val activity = it.context as AppCompatActivity activity.supportFragmentManager.beginTransaction() .replace(R.id.homepage, detailFragment) .commit() } // 初始状态显示规则 val currentCount = currentCartItem?.itemCount ?: 0 holder.amount_value.visibility = if (currentCount > 0) View.VISIBLE else View.GONE holder.button_remove_product.visibility = holder.amount_value.visibility holder.btn_add_product.setOnClickListener { val realPosition = holder.bindingAdapterPosition if (realPosition == RecyclerView.NO_POSITION) return@setOnClickListener val targetProduct = product[realPosition] // 匹配对应购物车条目做累加 val matchedItem = newitem.find { it.productId == targetProduct.id } val newCount = (matchedItem?.itemCount ?: 0) + 1 // 同步更新购物车条目数据 matchedItem?.itemCount = newCount // 更新UI显示 holder.amount_value.text = newCount.toString() holder.amount_value.visibility = View.VISIBLE holder.button_remove_product.visibility = View.VISIBLE } }
越界报错的根因说明
之前触发IndexOutOfBoundsException的核心原因是代码默认newitem的长度和product完全一致,但实际传入的newitem仅包含1个元素,数组最大合法索引为0;当滑动到列表第2个及之后的条目时,position会变为1、2甚至更大,直接取newitem[position]就会超出数组长度边界。
额外注意:如果newitem的内容会随加购操作动态变化,不要直接修改构造函数传入的原列表引用,需要给适配器增加专门的数据更新方法,替换内部的newitem实例后再触发UI刷新,避免数据不同步的问题。
内容的提问来源于stack exchange,提问作者bahador jadidoleslam
相关产品推荐
相关产品推荐

