如何使用Recyclerview Adapter获取购物车中的总数



嗨,我在我的Android应用程序中使用Recyclerview与适配器。在我的应用程序中,我有产品列表屏幕,用户可以在每个列表项目中设置数量。我使用两个imageview来增加和减少数量。现在的问题是,如果我为第一个产品制作2个数量,为第二个产品制作4个数量,那么我的购物车屏幕的总数应该是6,但我无法获得总数。下面是我的适配器代码,有人能帮我吗?

class ProductAdapter(private val cellClickListener: CellClickListener) : RecyclerView.Adapter<ProductViewHolder>() {
var productsList = mutableListOf<Product>()
var cartList = mutableListOf<Product>()
/* fun setMovieList(movies: List<MobileList>) {
this.movies = movies.toMutableList()
notifyDataSetChanged()
}*/
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 products = productsList[position]
holder.binding.name.text = products.name
holder.binding.price.text = products.price
Glide.with(holder.itemView.context).load(products.image_url).into(holder.binding.imageview)
var cartCount : Int=0

holder.binding.cartPlus.setOnClickListener {
cartCount++
holder.binding.cartValue.text = cartCount.toString()
cartList.add(products)
//println(cartList)
}
holder.binding.cartMinus.setOnClickListener {
cartCount--
holder.binding.cartValue.text = cartCount.toString()
cartList.remove(products)
// println(cartList)
}
fun updatedData( updatedcartList:List<Product>){
cartList.addAll(updatedcartList)
}
holder.itemView.setOnClickListener {
cellClickListener.onCellClickListener(products,cartCount)
}
}
override fun getItemCount(): Int {
return productsList.size
}

}
class ProductViewHolder(val binding: AdapterLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
}
interface CellClickListener {
fun onCellClickListener(data: Product,count:Int)
}

使用cartlist.size()作为总计数。为了在activity中使用,在Adapter类中定义:

class ProductAdapter(private val..
{
...
fun getCartSize():Int {
return cartlist.size()
}
...
}

在活动中你可以使用:

adapter.getCartsize()

因为您只是将列表传递到recycleview,并希望在片段或活动中使用它。我建议你用这个清单来计算你的商品总数。您可以使用sumOf到您的列表。

你可以这样使用它,在你传递到循环视图之前。

val totalCount = list.sumOf { it.quantity }

txtView.text = list.sumOf {it.quantity}.toString()

最新更新