<html>
<body>
<h1>Submit the Form</h1>
<form action="/hello" method="POST">
file to download: <input type="text" name="greet">
<br/>
<input type="submit">
</form>
</body>
</html>
如果在[afterTextChanged]中设置了文本agian,程序将再次调用event。
如何在afterTextChanged中格式化EditText的内容?
答案 0 :(得分:1)
与@Bojan Kseneman建议一样,boolean
标志解决了这个问题。
boolean enableChangeListener = true;
txt1.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void afterTextChanged(Editable s) {
if(enableChangeListener){
enableChangeListener = false;
String value = txt1.getText().toString();
txt1.setText(String.valueOf(Utilities
.roundOneDecimals(Double.parseDouble(value))));
}
}
});
答案 1 :(得分:0)
我一直在我的项目中使用它,它可以正常工作。像editText.addTextChangesLisener(new MyTextWatcher(editText));
然而正如我在评论中提到的,一个简单的布尔fflag将解决你的问题。
public class MyTextWatcher implements TextWatcher {
private final WeakReference<EditText> editTextWeakReference;
public MyTextWatcher(EditText editText) {
editTextWeakReference = new WeakReference<EditText>(editText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
EditText editText = editTextWeakReference.get();
if (editText == null) return;
String s = editable.toString();
editText.removeTextChangedListener(this);
// Do your formatting here
editText.setText(String.valueOf(Utilities
.roundOneDecimals(Double.parseDouble(s))));editText.setSelection(editText.getText().toString.length());
editText.addTextChangedListener(this);
}
}