【问题标题】:How to sum and multiply values from TextViews in ListView and display them in a toast?如何在 ListView 中对 TextViews 中的值进行求和和相乘并将它们显示在 toast 中?
【发布时间】:2019-03-02 12:10:58
【问题描述】:

我是编程新手,如果您能帮助我,那就太好了。我有一个 Activity,它有一个按钮和一个列表视图。列表视图上的值是名称、价格、类别和数量,并通过适配器定义。我想知道如何将每行的数量值乘以价格值并将所有这些值相加,并在单击按钮时将结果显示在吐司中。 Here's 它的图形以便更好地理解它。

代码如下:

CartListActivity.java

public class CartListActivity extends AppCompatActivity {

    ListView userList;
    UserCustomAdapter userAdapter;
    ArrayList<User> userArray = new ArrayList<User>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_list);

        Button payBtn = (Button)findViewById(R.id.payBtn);
        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Total: x€", Toast.LENGTH_SHORT).show();
            }
         });

        /**
         * add item in arraylist
         */
        userArray.add(new User("Olives verdes", "1,20€", "Aperitius", "0"));
        userArray.add(new User("Olives negres", "1,30€", "Aperitius", "0"));
        userArray.add(new User("Cogombrets", "1,80€", "Aperitius","0"));
        userArray.add(new User("Patates Lay's", "1,19€", "Aperitius","0"));
        userArray.add(new User("Potet", "0,95€", "Bebè","0"));
        userArray.add(new User("Biberó", "3,85€", "Bebè","0"));
        userArray.add(new User("Tovalloletes", "1,10€", "Bebè","0"));
        userArray.add(new User("Perxes de nadó", "1,95€", "Bebè","0"));
        /**
         * set item into adapter
         */
        userAdapter = new UserCustomAdapter(CartListActivity.this, R.layout.view_row,
                userArray);
        userList = (ListView) findViewById(R.id.listView);
        userList.setItemsCanFocus(false);
        userList.setAdapter(userAdapter);
        /**
         * get on item click listener
         */
        userList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    final int position, long id) {
                Log.i("List View Clicked", "**********");
                Toast.makeText(CartListActivity.this,
                        "List View Clicked:" + position, Toast.LENGTH_LONG)
                        .show();
            }
        });

    }

}

UserCustomAdapter.java

public class UserCustomAdapter extends ArrayAdapter<User> {
    Context context;
    int layoutResourceId;
    ArrayList<User> data = new ArrayList<User>();

    public UserCustomAdapter(Context context, int layoutResourceId,
                             ArrayList<User> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        UserHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new UserHolder();
            holder.textName = (TextView) row.findViewById(R.id.textView1);
            holder.textPrice = (TextView) row.findViewById(R.id.textView2);
            holder.textCategory = (TextView) row.findViewById(R.id.textView3);
            holder.textQuantity = (TextView) row.findViewById(R.id.quantityTxt);
            holder.btnEdit = (Button) row.findViewById(R.id.button1);
            holder.btnDelete = (Button) row.findViewById(R.id.button2);
            row.setTag(holder);
        } else {
            holder = (UserHolder) row.getTag();
        }
        final User user = data.get(position);
        holder.textName.setText(user.getName());
        holder.textPrice.setText(user.getPrice());
        holder.textCategory.setText(user.getCategory());
        holder.textQuantity.setText(user.getQuantity());
        final UserHolder finalHolder = holder;
        holder.btnEdit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String value1 = finalHolder.textQuantity.getText().toString();
                int a = Integer.parseInt(value1);

                if(a <= 99) {
                    int sum = a + 1;

                    Log.i("Edit Button Clicked", "**********");
                    user.setQuantity(Integer.toString(sum));
                    finalHolder.textQuantity.setText(Integer.toString(sum));
                }
            }
        });
        holder.btnDelete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                    String value2 = finalHolder.textQuantity.getText().toString();
                    int a = Integer.parseInt(value2);

                    if(a > 0) {
                        int substract = a - 1;
                        Log.i("Delete Button Clicked", "**********");
                        user.setQuantity(Integer.toString(substract));
                        finalHolder.textQuantity.setText(Integer.toString(substract));
                    }
            }
        });
        return row;

    }

    static class UserHolder {
        TextView textName;
        TextView textPrice;
        TextView textCategory;
        TextView textQuantity;
        Button btnEdit;
        Button btnDelete;
    }
}

用户.java

public class User {
    String name;
    String price;
    String category;
    String quantity;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public User(String name, String price, String category, String quantity) {
        super();
        this.name = name;
        this.price = price;
        this.category = category;
        this.quantity = quantity;
    }

}

【问题讨论】:

    标签: java android arrays listview


    【解决方案1】:

    希望我没有理解您的问题,如果您遍历 payBtn onClick 方法中的 userArray 列表并获得总和怎么办? 像这样:

    Button payBtn = (Button)findViewById(R.id.payBtn);
        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int total = 0;
                for(User u: userArray){
                    total += (u.getPrice()*u.getQuantity());
                }
    
                Toast.makeText(getApplicationContext(), "Total: +total+"€", Toast.LENGTH_SHORT).show();
            }
         });
    

    【讨论】:

    • 感谢您的帮助!在这里,我在 '(u.getPrice()*u.getQuantity());' 中遇到错误并在 'Toast.makeText(getApplicationContext(), "Total: +total+"€", Toast.LENGTH_SHORT).show();'虽然
    • 你能说出出现了什么错误吗?所以我可以帮你
    【解决方案2】:
        yourButton.setOnClickListener(new View.OnClickListener() {
            long total=0;
            for(User u:userArray){
              String priceAsString=u.getPrice();
              String priceWithOutCamma=priceAsString.replaceAll(",","");
              String priceWithOutSign=priceWithOutCamma.replaceAll("€","");
              int price=Integer.valueOf("priceWithOutSign");
              int quantity=Integer.valueOf(u.getQuantity());
              total+=price*quantity;
           }
        DecimalFormat format=new DecimalFormat("#,###");
        String totalFormatted=format.format(total);
        Toast.makeText(getApplicationContext(), "Total: " +totalFormatted+"€", Toast.LENGTH_SHORT).show();
    }
    

    【讨论】:

      【解决方案3】:

      所以对于您的设计,正如我在您的代码中看到的那样,您有一个 arrayList 包含您创建的所有项目。 我会做这样的事情(在你的活动类中创建这个函数):

      public class CartListActivity extends AppCompatActivity {
      
      ListView userList;
      UserCustomAdapter userAdapter;
      ArrayList<User> userArray = new ArrayList<User>();
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_cart_list);
      
          Button payBtn = (Button)findViewById(R.id.payBtn);
          payBtn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Toast.makeText(getApplicationContext(), "Total: x€", Toast.LENGTH_SHORT).show();
              }
           });
      
          /**
           * add item in arraylist
           */
          userArray.add(new User("Olives verdes", "1,20€", "Aperitius", "0"));
          userArray.add(new User("Olives negres", "1,30€", "Aperitius", "0"));
          userArray.add(new User("Cogombrets", "1,80€", "Aperitius","0"));
          userArray.add(new User("Patates Lay's", "1,19€", "Aperitius","0"));
          userArray.add(new User("Potet", "0,95€", "Bebè","0"));
          userArray.add(new User("Biberó", "3,85€", "Bebè","0"));
          userArray.add(new User("Tovalloletes", "1,10€", "Bebè","0"));
          userArray.add(new User("Perxes de nadó", "1,95€", "Bebè","0"));
          /**
           * set item into adapter
           */
          userAdapter = new UserCustomAdapter(CartListActivity.this, R.layout.view_row,
                  userArray);
          userList = (ListView) findViewById(R.id.listView);
          userList.setItemsCanFocus(false);
          userList.setAdapter(userAdapter);
          /**
           * get on item click listener
           */
          userList.setOnItemClickListener(new OnItemClickListener() {
      
              @Override
              public void onItemClick(AdapterView<?> parent, View v,
                                      final int position, long id) {
                  Log.i("List View Clicked", "**********");
                  Toast.makeText(CartListActivity.this,
                          "List View Clicked:" + position, Toast.LENGTH_LONG)
                          .show();
              }
          });
      
      }
      private double getTotalPrice(){
          double total = 0;
          if (userArray.size() == 0){ return total;}
          else {
              for (User user : userArray ) {
                  double price = Double.parseDouble(user.getPrice()); // assuming you price is a string , and that you have getters and setters for all of the user's fields
                  int quantity = Integer.parseInt(user.getQuantity());
                  total = price*quantity;
              }
              return total;
          }
      

      }

      (如果语法有问题,我会编辑我的答案) 然后在您的 onClick 中:

              payBtn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  double totalPrice = getTotalPrice();
                  String msg = String.format("Total: %f€" , totalPrice ) // %f because the function returns double
                  Toast.makeText(getApplicationContext(), msg , Toast.LENGTH_SHORT).show();
              }
           });
      

      【讨论】:

      • 非常感谢您的帮助。我在适配器中没有收到任何错误,但在 onClick 中它说无法解析方法“getTotalPrice()”
      • 我已经编辑了我的答案,向您展示应该将 getTotalPrice 函数粘贴到哪里。
      • 现在它在 getTotalPrice() 中显示“无法解析符号数据”。我不知道是我做错了什么还是我错过了什么。很抱歉给您带来不便
      • switch 'data' with 'userArray' by data 我的意思是你的 arrayList 的名称,我会再次编辑我的答案。
      • 现在没有错误,但是当我触摸按钮时应用程序崩溃了。可能是因为我没有设置 getter 或 setter 吗?我是新手,我不知道这些是什么意思
      猜你喜欢
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多