Java 货币格式仅适用于一个动态编辑文本,不适用于其他动态编辑文本

Java 货币格式仅适用于一个动态编辑文本,不适用于其他动态编辑文本,java,android,android-edittext,textwatcher,Java,Android,Android Edittext,Textwatcher,以下for循环根据项目的大小添加x行数: for (int i = 0; i < shoppingQuantityAndItems.size(); i++) { TableRow label = new TableRow(this); EditText quantity = new EditText(this); quantity.setInputType(InputType.TYPE_CLASS_NUMBER); quantity.setText(sho

以下
for
循环根据项目的大小添加
x
行数:

for (int i = 0; i < shoppingQuantityAndItems.size(); i++) {
    TableRow label = new TableRow(this);

    EditText quantity = new EditText(this);
    quantity.setInputType(InputType.TYPE_CLASS_NUMBER);
    quantity.setText(shoppingQuantityAndItems.get(i).get(0));
    System.out.println("Size: "
            + shoppingQuantityAndItems.get(i).get(0));
    label.addView(quantity);

    TextView items = new TextView(this);
    items.setText(shoppingQuantityAndItems.get(i).get(1));
    System.out.println("Item: "
            + shoppingQuantityAndItems.get(i).get(1));
    label.addView(items);

    price = new EditText(this);
    price.setId(i);
    price.setInputType(InputType.TYPE_CLASS_NUMBER
            | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    price.setText("");
    label.addView(price);
    updatePrice(price.getId());

    CheckBox ch = new CheckBox(this);
    ch.setChecked(false);
    label.addView(ch);

    table.addView(label);
}

我只是想知道是否有人能告诉我,当我在这些文本字段中输入一个数字时,如何确保只有该值改变,而不是其他值改变。

您使用了错误的
EditText
小部件

updatedPrice
可能是类的数据成员。这不是一个好主意,因为您没有这些
EditText
小部件中的一个

此外,您的
onTextChanged()
假设
updatedPrice
将指向右侧的
EditText
小部件,即用户碰巧正在键入的小部件,从统计上讲,这是不可能的

假设代码的其余部分实际上是您想要的,那么您需要更改:

updatedPrice = (EditText) price.findViewById(id);
将是:

final EditText updatedPrice = (EditText) price.findViewById(id);
这将导致您的
TextWatcher
匿名内部类使用在调用
updatePrice()
时检索到的
updatePrice
,而不是类的数据成员中的一些随机
EditText

或者,您可以让
TextWatcher
自己执行
findViewById()
。任何一种方法都应该有效


我建议您删除
updatedPrice
数据成员,并修复其余的代码,因为您可能会有其他类似的错误。

谢谢您的帮助。删除updatedPrice时,我会做任何最终决定吗?我该如何让TextWatcher执行findViewById()?@Jonathanines:“删除updatedPrice时,我会将任何内容设置为最终值吗?”——如果您遵循我的第一个建议,您将创建一个名为
updatedPrice
的局部变量,并将其设置为
final
。“我如何让TextWatcher执行findViewById()?”——在
onTextChanged()
方法中添加对
findViewById()
的调用。您需要在方法参数中将
int-id
设置为
final int-id
final EditText updatedPrice = (EditText) price.findViewById(id);