首页 > 解决方案 > 添加 RecyclerView 项目总计

问题描述

在我的项目中,我有一个包含适配器和片段类的回收器视图。一切都按预期工作,我正在尝试对特定列值求和并将其显示在文本字段中。我尝试了以下总方法,但它不起作用。任何帮助表示赞赏。

使用的语言

Kotlin

使用的代码

适配器类

   override fun onBindViewHolder(holder: ViewHolder, position: Int)
    {
        holder.bindcar(list[position],fragment)

    }
    fun bindcar(Test: TestCart?, fragment: TestFragment)=with(carView)
        {
            TestName.text=Test?.carName
            TestQuantity.text= Test?.carQuantity.toString()
            TestPrice.text= Test?.carPrice!!.toString()
        }

分段

for (c in carList!!.iterator())
    {
            val car=TestCart()

            //var carPrice=0
            car.carName=c.carName
            car.carQuantity=c.carQuantity
            car.carPrice=c.carPrice
           // car.carPrice= c.carPrice!! +Price
            carListcars!!.add(car)
    }
    adapter!!.notifyDataSetChanged()
    }

期待

Total CarPrice in the Recycler View.

标签: androidandroid-fragmentskotlinandroid-recyclerview

解决方案


你可以使用 Kotlin List 的 sumBy 方法来做到这一点。

在您的片段类中添加以下代码

for (c in carList!!.iterator())
  {
      val car=TestCart()

            //var carPrice=0
            car.carName=c.carName
            car.carQuantity=c.carQuantity
            car.carPrice=c.carPrice
           // car.carPrice= c.carPrice!! +Price
            carListcars!!.add(car)
    }

    adapter!!.notifyDataSetChanged()

    // sumby code 
    var totalAmount: Int = carListcars.sumBy{ it.carPrice }

    // setting your textView
    TestPrice.text = totalAmount.toString()


    }

推荐阅读