我想计算所有项目的总和并将它们显示在烤面包中,如何计算它们?
那是我的onBindViewHolder
@Override
public void onBindViewHolder(@NonNull ViewHolder_chart viewHolder_chart, int i) {
viewHolder_chart.p_name_CHART_tv.setText(_chartdata.get(i).getName_prdct()); // set name of product
//Replace these two methods
viewHolder_chart.p_price_CHART_tv.setText(_chartdata.get(i).getPrice_prdct()); // set quantity
viewHolder_chart.p_quantity_Chart_tv.setText(_chartdata.get(i).getUnit_prdct()); // set price
////////////////////////////////
viewHolder_chart.p_totalITem_CHART_tv.setText(_chartdata.get(i).getTotal_quantity());
Log.d("Adapter_chart","bitmap="+_chartdata.get(i).getImage_prdct());
viewHolder_chart.p_img_CHART.setImageBitmap(_chartdata.get(i).getImage_prdct());
total += _chartdata.get(i).getPrice_prdct();
if(i==_chartdata.size()-1){//check if list last element
//show your total count view here---- and add total amount
Toast.makeText(context, "t="+total, Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
首先从onBindViewHolder中删除以下行:
total += _chartdata.get(i).getPrice_prdct();
因为onBindViewHolder会在您每次滚动并尝试恢复视图位置时调用,因此我们在这里无法进行此类操作,例如产品总和,数量或总和等。
public int getMyTotalQuantity(){
int totalQuantity = 0;
for(int i=0; i<_chartdata.size(); i++){
if(_chartdata.get(i) != null && _chartdata.get(i).getTotal_quantity() != null &&
!TextUtils.isEmpty(_chartdata.get(i).getTotal_quantity())){
totalQuantity = totalQuantity + Integer.parseInt(_chartdata.get(i).getTotal_quantity());
}
return totalQuantity;
}
如果要最后显示数量总计的视图,则可以声明上述方法,然后在onBindViewHolder中使用它,如下所示:
if(i==_chartdata.size()-1){//check if list last element
// to get total quantity
Toast.makeText(context, "total quantity = " + getMyTotalQuantity(), Toast.LENGTH_SHORT).show();
}
您可以创建相同的方法来获取金额总和,并将其用于绑定视图持有人。