On Button Click how to increment counter and show in textview

前端 未结 4 1949
天涯浪人
天涯浪人 2021-01-22 06:58

I am working on a shopping cart assignment for that I have created a custom ListView that contains the Picture, Price and Add to Cart button in each row. I also have a textview

4条回答
  •  一个人的身影
    2021-01-22 07:33

    Make sure you have reference to your TextView in xml.

    Connect it (using findViewById()) inside onCreate() of Activity only, and you may pass it to your Adapter (i.e making a class field and setter getter method), if Adapter is a separate class.

    and dont do this inside getView() of Adapter, remove this line.

    final TextView tv  = (TextView)convertView.findViewById(R.id.tvCount);
    

    you will pass your TextView from Activity to Adapter using constructor or setter getter method, will keep a reference using class Adapter's class level variable and the what you will do inside onClick() of Button is:

    btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
              count++;
             yourClassLevelTextView.setText(String.valueOf(count));
         }});
    

    EDIT:

    how you will pass TextView to Adapter

    public class YourAdapter extends BlahBlahBlah
    {
         private TextView yourClassLevelTextView;
         public void setTextView(TextView textViewFromActivity)
         {
             this.yourClassLevelTextView = textViewFromActivity;
         }
    }
    

    and in Activity do something like this:

    YourAdapter adapter = new YourAdapter(blah, blah, blah);
    adapter.setTextView(yourTextViewInActivity);
    listView.setAdapter(adapter);
    

提交回复
热议问题