嗨,我在我的 Android 应用程序中使用 Recyclerview 和 Adapter。在我的应用程序中,我有产品列表屏幕,用户可以在其中设置每个列表项中的数量。我使用两个图像视图来增加和减少数量。现在的问题是,如果我为第一个产品制作 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()
的总数。为了在活动中使用,在 Adapter 类中定义它:
class ProductAdapter(private val..
{
...
fun getCartSize():Int {
return cartlist.size()
}
...
}
在活动中,您可以使用:
adapter.getCartsize()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句