我的应用中有一个购物车,我一直想知道如何从listview中的textviews中获取值的总和,然后将其显示在另一个类中?
orderTotal 数组是每行中产品数量
这是我的适配器类:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderTotal;
public ListCartAdapter(Context context, ArrayList<String> orderTotal){
this.context = context;
this.orderTotal = orderTotal;
}
@Override
public int getCount() {
return orderName.size();
}
@Override
public Object getItem(int position) {
return orderName.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final cartDatabaseHelper db = new cartDatabaseHelper(context);
final View listView;
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView total = (TextView) listView.findViewById(R.id.textOrderTotal);
total.setText(orderTotal.get(position));
return listView;
}
这是MainActivity类:
//CART LISTVIEW
private ArrayList<String> orderid;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
private ArrayList<String> orderTotal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//CART LISTVIEW
orderid = new ArrayList<>();
orderName = new ArrayList<>();
orderSize = new ArrayList<>();
orderQuantity = new ArrayList<>();
orderTotal = new ArrayList<>();
TextView textTotal = (TextView) findViewById(R.id.textOrderSumTotal);
ListView listView = (ListView) findViewById(R.id.listView);
ListCartAdapter adapter = new ListCartAdapter(cart.this, orderid, orderName, orderSize, orderQuantity, orderTotal);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
if(data.getCount() == 0){
btnCheckout.setVisibility(View.GONE);
}
else
{
btnCheckout.setVisibility(View.VISIBLE);
data.moveToFirst();
do{
orderid.add(data.getString(0));
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
orderTotal.add(data.getString(4));
} while (data.moveToNext());
}
data.close();
listView.setEmptyView(findViewById(R.id.emptyView));
}
textTotal是我计划显示listview中值的总和。
有人能指出我正确的方向吗?提前谢谢!
答案 0 :(得分:1)
如果您列出的数组orderTotal
中列出的所有价格都很简单。迭代列表并添加以下所有值:
int total = 0;
for(String s : orderTotal){
total += Integer.parseInt(s);
}
在任意位置显示此total
。如果价格是浮动的,那么使用Float.parseFloat(YOUR_FLOAT_STRING)
;