You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过RecyclerView Adapter获取购物车商品总数量

问题根源

现有代码的核心问题有3个:

  • cartCount是onBindViewHolder中的局部变量,RecyclerView滚动时ViewHolder会被复用,之前设置的商品数量会直接丢失,同时UI显示也会错乱
  • 直接往cartList中反复添加/移除同一个商品对象,当同一个商品添加多次时,调用remove()只会移除列表中第一个匹配的商品,无法和实际选择的数量对应
  • 没有持久化存储每个商品对应的购买数量,无法统一汇总计算总数

解决方案

第一步:改造数据存储结构

优先给Product实体类新增一个buyCount字段,用来存储每个商品的购买数量:

data class Product(
    // 原有字段不变:id、name、price、image_url等
    var buyCount: Int = 0 // 新增购买数量字段,默认0
)

如果不想修改原有的Product类,也可以在Adapter中新增一个HashMap<Long, Int>来存储商品ID对应的购买数量。

第二步:修改Adapter逻辑

修改后的Adapter代码如下:

class ProductAdapter(private val cellClickListener: CellClickListener) : RecyclerView.Adapter<ProductViewHolder>() {
    var productsList = mutableListOf<Product>()

    fun addData(data:List<Product>){
        productsList.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = AdapterLayoutBinding.inflate(inflater, parent, false)
        return ProductViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        val product = productsList[position]
        holder.binding.name.text = product.name
        holder.binding.price.text = product.price
        Glide.with(holder.itemView.context).load(product.image_url).into(holder.binding.imageview)
        // 绑定当前商品的已选数量,解决ViewHolder复用显示错乱问题
        holder.binding.cartValue.text = product.buyCount.toString()

        holder.binding.cartPlus.setOnClickListener {
            product.buyCount++
            holder.binding.cartValue.text = product.buyCount.toString()
        }

        holder.binding.cartMinus.setOnClickListener {
            if (product.buyCount > 0) { // 避免数量减到负数
                product.buyCount--
                holder.binding.cartValue.text = product.buyCount.toString()
            }
        }

        holder.itemView.setOnClickListener {
            cellClickListener.onCellClickListener(product, product.buyCount)
        }
    }

    override fun getItemCount(): Int = productsList.size

    // 新增获取购物车总数量的方法,外部直接调用即可拿到总计数
    fun getTotalCartCount(): Int {
        var total = 0
        productsList.forEach { 
            total += it.buyCount 
        }
        return total
    }

    // 新增获取已选商品列表的方法,需要传给购物车页时调用
    fun getSelectedProducts(): List<Product> {
        return productsList.filter { it.buyCount > 0 }
    }
}

class ProductViewHolder(val binding: AdapterLayoutBinding) : RecyclerView.ViewHolder(binding.root)

interface CellClickListener {
    fun onCellClickListener(data: Product,count:Int)
}

第三步:获取总数量

在Activity/Fragment中需要获取总计数时,直接调用adapter.getTotalCartCount()即可拿到正确的总数量,跳转到购物车页时也可以调用getSelectedProducts()把已选商品列表传过去。


内容的提问来源于stack exchange,提问作者New Bee Andy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:27:02