I want to calculate the total cost once without repeating it every time we swipe the products
android swipe and avoid refreshing recyclerview items
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);
}
}
}
You shouldn't do any calculations in OnBindViewHolder(). That function is called every time you scroll up and down as views are recycled. Instead, I would suggest just calculating the total on initialization of the adapter
public CartAdapter(Context context, List<CartModel> cartModels) {
this.context = context;
this.cartModels = cartModels;
for (CartModel model : cartModels) {
total += model.getProductPrice();
}
// Set total textview
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.