gpt4 book ai didi

java - DecimalFormat 问题引发 StackOverFlowError?

转载 作者:太空狗 更新时间:2023-10-29 14:32:49 25 4
gpt4 key购买 nike

我有一个编辑文本。我想在其中输入十进制值。

那是我输入第一个数字的时候。它应该是这样的:.01

然后我输入了第二个数字。它应该是这样的:.12

然后是第三个。它应该是这样的:1.23

它会像这样......如何在 Android 平台 中实现这个场景。有什么想法吗?

编辑:

我试过这个。但是当我将字符串附加到 EditText 时,我得到了 StackOverFlowError。我在下面发布了我的代码:

amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try {
if (s.length() == 1) {
Float f = Float.parseFloat(s.toString()) / 100;
System.out.println(String.valueOf(f));
amount.setText("");
amount.append(String.valueOf(f));//getting stackoverflow error here
} else if (s.length() > 1) {
String str = s.toString().replace(".", "");
Float f = Float.parseFloat(str) / 100;
System.out.println(String.valueOf(f));
amount.setText("");
amount.append(String.valueOf(f));
}
} catch (Exception e) {

}
}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});

最佳答案

看,您正在为一个元素实现 TextChangedKListener,您正在其中更改元素文本。

所以,在这行

amount.setText("");
amount.append(String.valueOf(f))

正在调用您的 TextWatcher 实现(如您所见 herehere )。

正如您在第二个链接中看到的,afterTextChanged 方法的 API 文档警告您陷入无限循环的风险:

be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively

self afterTextChanged描述,在 TextWatcher API 文档中,推荐了一个解决方法来处理这个问题:

You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.

关于java - DecimalFormat 问题引发 StackOverFlowError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4930406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com