要获得总价

时间:2017-04-04 10:24:22

标签: android listview

我正在使用列表查看Srno,项目名称,数量和价格。我想在listview下面的Textview中添加价格并显示其总数。我已经尝试过但它在我的textview中显示0。当我点击textview时给我Toast的总价。我使用了setText,但总价格没有显示在Textview中。以下是我的代码 -

Trial.java

public class Trial extends Activity {
    ListView listnew;

    ArrayList<Integer> sr1;
    ArrayList<String> item1;
    ArrayList<Integer> data;
    ArrayList<Integer> price;

   TextView textViewTotalAmt,textViewamount;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trial);
        data = new ArrayList<>();
        price = new ArrayList<>();


        listnew = (ListView) findViewById(R.id.newlist);
        textViewTotalAmt=(TextView)findViewById(R.id.total);

        textViewamount=(TextView)findViewById(R.id.amountdisplay);
        textViewamount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Toast.makeText(Trial.this," "+getTotal(price),Toast.LENGTH_SHORT).show();
            }
        });
        textViewamount.setText(" "+getTotal(price));



        Bundle bundle = getIntent().getExtras();

        sr1 = bundle.getIntegerArrayList("sr");
        item1 = bundle.getStringArrayList("item");
        data = bundle.getIntegerArrayList("qty");
        price = bundle.getIntegerArrayList("price");

        ArrayList<Integer> qty = new ArrayList<>();
        ArrayList<String> name = new ArrayList<>();
        ArrayList<Integer> srn = new ArrayList<>();
        ArrayList<Integer> ps = new ArrayList<>();
        for(int i=0;i<data.size();i++){
            if(data.get(i)>0){
                qty.add(data.get(i));
                name.add(item1.get(i));
                srn.add(sr1.get(i));
                ps.add(price.get(i));
            }
        }



        sr1.clear();
        sr1.addAll(srn);
       item1.clear();
        item1.addAll(name);
       data.clear();
        data.addAll(qty);
       price.clear();
       price.addAll(ps);



        Custom_Trial ct = new Custom_Trial( this,sr1, item1, data, price);
        listnew.setAdapter(ct);
        getTotal(price);

    }




    public int getTotal(ArrayList<Integer> price){

        int total=0;
        for(int i=0;i<price.size();i++){
            total= total+Integer.parseInt(String.valueOf(price.get(i)));
        }
        return total;

    }

}

2 个答案:

答案 0 :(得分:0)

我认为你应该移动这行代码

textViewamount.setText(" "+getTotal(price));

到onCreate方法的末尾

Custom_Trial ct = new Custom_Trial( this,sr1, item1, data, price);
    listnew.setAdapter(ct);
    getTotal(price);
    textViewamount.setText(" "+getTotal(price));

答案 1 :(得分:0)

你的Toast有效,因为当你的所有物品都已膨胀时会发生onClick

但是,您尝试在onCreate()中将值设置为电视。当您拨打setText()时,您的ArrayList NULL ,因为您只是实例化它。将setText()移到onCreate()的末尾或处理后,将值插入ArrayList

或者如果您只想在有人点击电视后显示总价,请将setText()粘贴到onClick内,此处当前显示Toast