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

Android RecyclerView实现商品项动态计算总价功能求助

RecyclerView实时计算总价实现方案

核心思路

把商品数量存在数据模型中(避免ViewHolder复用导致数据丢失),每次商品增删、数量变更时,遍历所有商品重新计算总价,通过接口回调通知页面更新总价显示。


步骤1:修正数据模型(ProductListViewModel)

给模型添加数量字段,确保数据与UI绑定:

public class ProductListViewModel {
    private String productName;
    private String productBarcode;
    private String productPrice;
    // 默认数量为1
    private int quantity = 1;

    // 保留原有getter/setter,新增数量相关方法
    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    // 原有构造方法及其他getter/setter...
}

步骤2:给Adapter添加总价回调与计算逻辑

定义接口让Adapter将总价变化通知给页面,同时实现总价计算方法:

public class ListViewAdapter extends RecyclerView.Adapter<DemoVH> {

    private ArrayList<ProductListViewModel> productList;
    private Context mContext;
    private OnTotalPriceChangeListener priceChangeListener;

    // 总价回调接口
    public interface OnTotalPriceChangeListener {
        void onTotalPriceChanged(int totalPrice);
    }

    // 设置回调的方法
    public void setOnTotalPriceChangeListener(OnTotalPriceChangeListener listener) {
        this.priceChangeListener = listener;
    }

    public ListViewAdapter(ArrayList<ProductListViewModel> productList, Context context) {
        this.productList = productList;
        this.mContext = context;
        // 初始化时计算一次总价
        calculateTotalPrice();
    }

    // 计算总价的核心方法
    private void calculateTotalPrice() {
        int total = 0;
        for (ProductListViewModel product : productList) {
            try {
                // 实际项目建议用float/double处理带小数的价格
                int price = Integer.parseInt(product.getProductPrice());
                total += price * product.getQuantity();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        // 通知页面更新总价
        if (priceChangeListener != null) {
            priceChangeListener.onTotalPriceChanged(total);
        }
    }

    @NonNull
    @Override
    public DemoVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_view_row, parent, false);
        return new DemoVH(view).linkadapter(this);
    }

    @Override
    public void onBindViewHolder(@NonNull DemoVH holder, int position) {
        ProductListViewModel product = productList.get(position);
        holder.Product_Name.setText(product.getProductName());
        holder.Product_Barcode.setText(product.getProductBarcode());
        holder.Product_Price.setText(product.getProductPrice());
        // 绑定数量到UI
        holder.Product_QTY.setText(String.valueOf(product.getQuantity()));
    }

    @Override
    public int getItemCount() {
        return productList.size();
    }

    // 对外暴露的更新总价方法,比如添加商品后调用
    public void refreshTotalPrice() {
        calculateTotalPrice();
    }
}

步骤3:修改ViewHolder,操作模型中的数量

不再用ViewHolder局部变量存数量,直接操作模型数据,每次变更后触发总价计算:

class DemoVH extends RecyclerView.ViewHolder {
    TextView Product_Name;
    TextView Product_Barcode;
    TextView Product_Price;
    TextView Product_QTY;
    ImageView addQTY;
    ImageView lessQTY;
    private ListViewAdapter myAdapter;

    public DemoVH(@NonNull View itemView) {
        super(itemView);

        Product_Name = itemView.findViewById(R.id.ProductNameLbl);
        Product_Barcode = itemView.findViewById(R.id.ProductBarcodeLbl);
        Product_Price = itemView.findViewById(R.id.ProductPriceLbl);
        Product_QTY = itemView.findViewById(R.id.QTYLbl);
        addQTY = itemView.findViewById(R.id.AddQTYBtn);
        lessQTY = itemView.findViewById(R.id.lessQTYBtn);

        // 移除商品按钮逻辑
        itemView.findViewById(R.id.RemoveBtn).setOnClickListener(view -> {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                myAdapter.productList.remove(position);
                myAdapter.notifyItemRemoved(position);
                // 移除后重新计算总价
                myAdapter.calculateTotalPrice();
            }
        });

        // 增加数量逻辑
        addQTY.setOnClickListener(view -> {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                ProductListViewModel product = myAdapter.productList.get(position);
                int newQty = product.getQuantity() + 1;
                product.setQuantity(newQty);
                Product_QTY.setText(String.valueOf(newQty));
                // 数量变更后计算总价
                myAdapter.calculateTotalPrice();
            }
        });

        // 减少数量逻辑
        lessQTY.setOnClickListener(view -> {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                ProductListViewModel product = myAdapter.productList.get(position);
                int currentQty = product.getQuantity();
                if (currentQty > 1) {
                    int newQty = currentQty - 1;
                    product.setQuantity(newQty);
                    Product_QTY.setText(String.valueOf(newQty));
                    // 数量变更后计算总价
                    myAdapter.calculateTotalPrice();
                }
            }
        });
    }

    public DemoVH linkadapter(ListViewAdapter adapter) {
        myAdapter = adapter;
        return this;
    }
}

步骤4:在页面(Activity/Fragment)中使用

设置Adapter的回调,更新页面上的总价TextView:

// 假设页面中有显示总价的TextView
TextView totalPriceTv = findViewById(R.id.total_price_tv);

ListViewAdapter adapter = new ListViewAdapter(productList, this);
adapter.setOnTotalPriceChangeListener(totalPrice -> {
    totalPriceTv.setText("总价:" + totalPrice);
});
recyclerView.setAdapter(adapter);

// 添加新商品后,更新UI与总价
productList.add(newProduct);
adapter.notifyItemInserted(productList.size() - 1);
adapter.refreshTotalPrice();

关键注意点

  • 不要用ViewHolder局部变量存数量:RecyclerView的ViewHolder会复用,滑动后局部变量会重置,导致数据丢失。
  • 金额计算建议用float或double:实际项目中价格可能有小数,用int会丢失精度,记得处理格式化显示。
  • 异常处理:转换价格字符串时要捕获NumberFormatException,避免崩溃。

内容的提问来源于stack exchange,提问作者Mitch Serrano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:42:24