点击添加按钮时如何计算RecyclerView内商品总价并显示到TextView
问题原因
你当前实现的核心问题有两个:
- 总价变量
u_price是在添加按钮的点击事件内部声明的,每次点击都会被重置为0,只会累加当前单次添加的商品价格,无法保留之前的累计值。 - 删除商品的逻辑中没有同步更新总价,删除商品后总价不会对应减少。
解决方案
步骤1:封装统一的总价计算方法
在你的POS Fragment中新增一个公共方法,专门负责遍历商品列表计算总价并更新UI,保证添加、删除商品时总价计算逻辑统一:
// 统一计算并更新总价格 private void updateTotalPrice() { double totalPrice = 0.0; for (Products product : mainList) { // 转换商品售价为Double类型累加 totalPrice += Double.parseDouble(product.getSprice()); } // 更新总价显示控件 total.setText(String.valueOf(totalPrice)); }
步骤2:修改添加按钮的点击逻辑
去掉原来在点击事件内部声明的u_price变量,每次添加完商品后直接调用上面的总价更新方法:
btnAdd.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onClick(View v) { Cursor cursor = databaseHelper.getProduct(mBarcode.getText().toString()); if (cursor.moveToFirst()){ do { mBarcode.setText(""); Toast.makeText(getContext(), "Item added successfully", Toast.LENGTH_SHORT).show(); String id = cursor.getString(0); String barcode = cursor.getString(1); String name = cursor.getString(2); String oprice = cursor.getString(3); String sprice = cursor.getString(4); String date = cursor.getString(5); mainList.add(new Products(Integer.parseInt(id),1, barcode, name, "Total: K"+sprice, oprice, date)); } while(cursor.moveToNext()); // 新增商品后更新总价 updateTotalPrice(); }else { Toast.makeText(getContext(), "Item not found", Toast.LENGTH_LONG).show(); } } });
步骤3:修改删除逻辑,同步更新总价
在Adapter的删除点击事件中,删除商品后调用总价更新方法:
@Override public void onBindViewHolder(@NonNull POSAdapter.ProductViewHolder holder, int position) { Products products = mainList.get(position); holder.item.setText(products.getName()); holder.price.setText(products.getSprice()); holder.remove.setText("X"); holder.remove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mainList.remove(position); notifyItemRemoved(position); // 删除商品后更新总价 updateTotalPrice(); } }); }
注意事项
- 如果你的
Products类中保存的售价是带K这类货币符号的字符串,转Double前需要先去除符号,避免类型转换报错。 - 涉及金额计算推荐使用
BigDecimal代替Double,避免浮点运算精度丢失的问题。 - 直接遍历列表计算总价的方式更健壮,即使后续新增修改商品数量、清空列表等功能,只要调用该方法就能得到正确的总价。
内容的提问来源于stack exchange,提问作者Musanza
相关产品推荐
相关产品推荐

