删除 TextChangedListener 然后重新添加它
因此,我一直在尝试为 Android 实现 TextWatcher,但遇到了一些问题,因为 TextChangedListener 被多次调用或进入无限循环,因为我想将 EditText 小部件中的文本转换为货币格式的字符串。
我为解决此问题所做的工作是创建自己的自定义 TextWatcher,然后在 afterTextChanged 事件中执行类似以下操作
public class CurrencyTextWatcher implements TextWatcher {
private EditText et;
public CurrencyTextWatcher(EditText editText) {
et = editText;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
et.setText(myCurrencyString);
et.addTextChangedListener(this);
}
}
所以我的问题是,是否有更好的方法来做到这一点?我想要一个 EditText 小部件来保存编辑的位置以及生成的格式化字符串。
另外,像这样删除然后添加 TextChangedListener 实际上是否还会出现任何其他问题?
提前致谢
So I've been trying to implement the TextWatcher for Android and ran into a few problems with the TextChangedListener being called multiple times or going into an infinite loop as I want to convert the text in the EditText widget into a currency formatted string.
What I did to work around this was create my own custom TextWatcher and then in the afterTextChanged event did something like the following
public class CurrencyTextWatcher implements TextWatcher {
private EditText et;
public CurrencyTextWatcher(EditText editText) {
et = editText;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
et.setText(myCurrencyString);
et.addTextChangedListener(this);
}
}
So my question is, is there a better way of doing this? I want to have the one EditText Widget to hold where the edits go and the resulting formatted string.
Also is there actually any other issues that comes about removing and then adding a TextChangedListener like this?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次您更新(例如通过调用设置文本)您的 editText 时, afterTextChanged 都会被调用,所以我认为您应该避免每次在 afterTextChanged 中调用 setText ,而仅在某些内容真正发生变化时才调用它。
像这样
Everytime you will update (by eg calling set text) your editText the afterTextChanged will be called, so I think you should refrain from calling setText every time you are in afterTextChanged and only call it when something is really changing.
sth like this
跟随怎么样。
我学到的东西:不要低估 TextWatcher< /强> :D :D
How about following.
What I learn: Do not underestimate power of TextWatcher :D :D