在texttwatcher中更改文本后,EditText未更新



我有一个EditText和一个texttwatcher。

代码框架:

EditText x;
x.addTextChangedListener(new XyzTextWatcher());
XyzTextWatcher implements TextWatcher() {
    public synchronized void afterTextChanged(Editable text) {
        formatText(text);
    }
}

我的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++;
        }
    }
}

我的问题是-什么是显示在我的EditText不与可编辑的同步。当我调试代码时,我看到变量text (Editable)具有预期的值,但是EditText上显示的内容并不总是与edititable匹配。

例如,当我有一个文本X = "123-456-789"我手动从x中剪切文本"456"。格式化后,我的edit的值是"123-789-"然而,我的EditText上显示的值是"123—789"

它们在大多数情况下具有相同的值。

我假设EditText是可编辑的,它们应该总是匹配的。我错过什么了吗?

好的,你从来没有真正改变EditText只是edititable。Android的edittext不是edititable类的子类。字符串是edititable类的子类。onTextChangedListener不接收EditText作为参数,而是接收EditText中显示的可编辑/字符串。在你用连字符格式化edititable之后,你需要更新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);
        }
    }
}

为了防止减速,为什么不像这样改变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;
}

注意:我还没有测试过

最新更新