【问题标题】:android swipe and avoid refreshing recyclerview itemsandroid轻扫并避免刷新recyclerview项目
【发布时间】:2021-06-13 23:00:07
【问题描述】:

我想计算一次总成本,而不是每次刷产品时都重复一次

android 刷卡避免刷新recyclerview 项目

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
Context context;
List<CartModel> cartModels;
float total;
public CartAdapter(Context context, List<CartModel> cartModels) {
    this.context = context;
    this.cartModels = cartModels;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_product_layout, parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Glide.with(context).load(cartModels.get(position).getProductImg()).into(holder.productImg);
    holder.name.setText(cartModels.get(position).getProductName());
    holder.price.setText(cartModels.get(position).getProductPrice());
    holder.quantity.setText(String.valueOf(cartModels.get(position).getProductQuantity()));

    total += Float.parseFloat(String.valueOf(holder.price.getText()));

    Intent intent = new Intent("MyCart");
    intent.putExtra("total", total);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
@Override
public int getItemCount() {
    return cartModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView productImg;
    TextView name, price, quantity;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        productImg = itemView.findViewById(R.id.product_img);
        name = itemView.findViewById(R.id.product_name);
        price = itemView.findViewById(R.id.product_price);
        quantity = itemView.findViewById(R.id.product_quantity);
    }
}

}

显示刷屏前后的图片

【问题讨论】:

  • 这段代码中到底有什么不符合您的预期?告诉我们共享代码有什么问题。你有什么错误吗?

标签: java android firebase android-recyclerview


【解决方案1】:

您不应该在 OnBindViewHolder() 中进行任何计算。当视图被回收时,每次向上和向下滚动时都会调用该函数。相反,我建议只计算适配器初始化的总数

public CartAdapter(Context context, List<CartModel> cartModels) {
    this.context = context;
    this.cartModels = cartModels;
    for (CartModel model : cartModels) {
        total += model.getProductPrice();
    }
    // Set total textview

}

【讨论】:

  • 我实现了这个,但它只计算开始出现的产品,滚动屏幕后它不计算下面的其余产品
  • @YousefHashem 您是否在除初始化之外的其他地方向列表中添加了更多项目?如果是这样,只需创建一个 add 函数,每次将项目添加到数组时都会将价格添加到总数中
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多