[英]Setting an EditText's value to its own value, modified - causes to freeze
I'm trying to have an EditText with a number, and when the user types a number - commas will automatically be added, using a regular expression pattern. 我正在尝试使用带有数字的EditText,并且当用户键入数字时-将使用正则表达式模式自动添加逗号。
This is what I've tried: 这是我尝试过的:
input.addTextChangedListener(new TextWatcher() {
...
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (input.getText().toString().length() >= 4)
input.setText(addComma(input.getText().toString()));
}
...
}
addComma(String): addComma(String):
public String addComma(String number) {
return number.replace(",", "").replaceAll("\\B(?=(\\d{3})+(?!\\d))", ",");
}
When typing a number with 4 digits - the app is freezing and crashing after a while. 输入4位数字时-该应用程序冻结并在一段时间后崩溃。
Because you have an infinite loop in your application. 因为您的应用程序中存在无限循环。 When you set the text of a
TextView
your text changes and therefore the onTextChanged
method is called again causing the text to be changed again etc. etc. 当您设置
TextView
的文本时,您的文本会更改,因此再次调用onTextChanged
方法,导致文本再次更改, onTextChanged
。
You could use some boolean value which tests wether the text is already edited and only call it when it is not just edited by your method. 您可以使用一些布尔值来测试文本是否已被编辑,并且仅在不仅仅由您的方法编辑文本时才调用它。
Create a field in your class: 在您的班级中创建一个字段:
private boolean justEdited = false;
And use it in your listener: 并在您的监听器中使用它:
input.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (input.getText().toString().length() >= 4 && !justEdited) {
justEdited = true;
input.setText(addComma(input.getText().toString()));
} else if (justEdited) {
justEdited = false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.