我无法在 Edittext 中添加两位数并计算最终价格。我对一位数字没有任何问题。但是当我想添加两位数时我的应用程序关闭了。
edt_value.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (TextUtils.isEmpty(edt_value.getText())){
edt_value.clearFocus();
txt_finalprice.setText(gl_price.toString());
}else {
if(getCurrentFocus() == edt_value) {
int value = Integer.parseInt(edt_value.getText().toString().trim());
int price = Integer.parseInt(txt_finalprice.getText().toString().trim());
txt_finalprice.setText(value * price + "$");
}
}
}
});
最佳答案
您可能会使用Double.parseDouble
而不是Integer.parseInt
得到超出整数范围的计算数据
更新
这是这段代码中的问题:
int value = Integer.parseInt(edt_value.getText().toString().trim());
int price = Integer.parseInt(txt_finalprice.getText().toString().trim());
txt_finalprice.setText(value * price + "$");
您从 txt_finalprice 中获取价格,一开始没问题,然后在最后一个语句中,您将值*价格+“$”设置为 txt_finalprice,现在 txt_finalprice 有一些数字和 $(例如:30$),当您再次在编辑文本中输入一些内容,这一次您将 txt_finalprice
值转换为价格,但这会引发异常,因为 txt_finalprice 包含 $ 并且无法转换为 int。
您需要将 txt_finalprice
值存储到变量中。
关于java - 如何在Edittext afterTextChanged 中使用两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54931813/