如何转换为在 textView 中设置

How to cast int to set inside textView

当我将 productQuantity 字符串更改为整数时出现问题,应用程序崩溃,我无法理解错误,但他引导我到这里:

holder.quantity.setText(currentItem.getProductQuantity());

当我施放 setText(currentItem.getProductQuantity()) 时它不起作用

package com.original.original.original.admin;

public class ProductItem {
    String productName;
    String productCode;

    String productBuyPrice;
    String productSalePrice;
    int productQuantity;
    private String key;

    public ProductItem() {
    }

    public ProductItem(String productName, String productCode, String productBuyPrice, String productSalePrice, int productQuantity) {
        this.productName = productName;
        this.productCode = productCode;
        this.productBuyPrice = productBuyPrice;
        this.productSalePrice = productSalePrice;
        this.productQuantity = productQuantity;
    }

//    @Exclude
    public String getKey() {
        return key;
    }

//    @Exclude
    public void setKey(String key) {
        this.key = key;
    }

    public String getProductCode() {
        return productCode;
    }

    public String getProductName() {
        return productName;
    }

    public String getProductBuyPrice() {
        return productBuyPrice;
    }

    public String getProductSalePrice() {
        return productSalePrice;
    }

    public int getProductQuantity() {
        return productQuantity;
    }
}

和这个onBindView方法

@Override
    public void onBindViewHolder(productViewHolder holder, int position) {
        ProductItem currentItem = items.get(position);

        holder.name.setText(currentItem.getProductName());
        holder.code.setText(currentItem.getProductCode());
        holder.buyPrice.setText(currentItem.getProductBuyPrice());
        holder.salePrice.setText(currentItem.getProductSalePrice());
        holder.quantity.setText(currentItem.getProductQuantity());


    }

尝试String.valueOf(YOUR_VALUE);

类似于textView.setText(String.valueOf(7));

我想在你的情况下,

holder.quantity.setText(String.valueOf(currentItem.getProductQuantity()));

From android documentation 设置文本(int resid) 使用字符串资源标识符设置要显示的文本。

它崩溃是因为,系统认为您正在调用 textview.setText(int resId) 方法并尝试查找具有您作为整数传递给 setText() 的 ID 的资源。

因此在将其设置为文本视图之前,您需要将数字转换为字符串。

只需转换此行:

holder.quantity.setText(currentItem.getProductQuantity());

holder.quantity.setText(currentItem.getProductQuantity()+"");

它会工作,但产品数量应该始终得到警告和 return 整数,否则应用程序将崩溃

如果您确定 "holder.quantity" 和 "currentItem" 不为空,请使用此代码

holder.quantity.setText(String.valueOf(currentItem.getProductQuantity()));