Kar*_*thz 4 android textwatcher android-edittext
我有一个EditText和一个TextWatcher.
我的代码的骨架:
EditText x;
x.addTextChangedListener(new XyzTextWatcher());
XyzTextWatcher implements TextWatcher() {
public synchronized void afterTextChanged(Editable text) {
formatText(text);
}
}
Run Code Online (Sandbox Code Playgroud)
我的formatText()方法在文本的某些位置插入一些连字符.
private void formatText(Editable text) {
removeSeparators(text);
if (text.length() >= 3) {
text.insert(3, "-");
}
if (text.length() >= 7) {
text.insert(7, "-");
}
}
private void removeSeparators(Editable text) {
int p = 0;
while (p < text.length()) {
if (text.charAt(p) == '-') {
text.delete(p, p + 1);
} else {
p++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是 - 我的EditText上显示的内容与Editable不同步.当我调试代码时,我看到变量文本(可编辑)具有预期值,但EditText上显示的内容并不总是与Editable相匹配.
例如,当我有一个文本x ="123-456-789"时,我手动从x剪切文本"456".格式化后,我的可编辑值为"123-789-"但是,我的EditText上显示的值是"123--789"
但是在大多数情况下它们具有相同的值.
我假设EditText是可编辑的,它们应该始终匹配.我错过了什么吗?
好吧,你从来没有真正改变EditText只是可编辑.Android EditTexts不是Editable类的子项.字符串是Editable类的子类.onTextChangedListener不接收EditText作为参数,而是接收EditText中显示的Editable/String.使用连字符格式化可编辑后,您需要更新EditText.像这样的东西应该工作正常:
class MyClass extends Activity{
//I've ommited the onStart(), onPause(), onStop() etc.. methods
EditText x;
x.addTextChangedListener(new XyzTextWatcher());
XyzTextWatcher implements TextWatcher() {
public synchronized void afterTextChanged(Editable text) {
String s = formatText(text);
MyClass.this.x.setText(s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了防止减速,为什么不改变formatText方法呢?
private Editable formatText(Editable text) {
int sep1Loc = 3;
int sep2Loc = 7;
if(text.length==sep1Loc)
text.append('-');
if(text.length==sep2Loc)
text.append('-');
return text;
}
Run Code Online (Sandbox Code Playgroud)
注意:我没有测试过这个
| 归档时间: |
|
| 查看次数: |
13695 次 |
| 最近记录: |