Android中在onTextChanged中调用setText方法

4
为了防止无限循环,我做了一些非常丑陋的事情...
    @Override
protected void onTextChanged(CharSequence text, int start,
        int lengthBefore, int lengthAfter) {

    String t = text.toString();
    String tt = t.toUpperCase();

    if (!t.equals(tt)) {

        setText(tt);
    }

    super.onTextChanged(text, start, lengthBefore, lengthAfter);
}

有没有其他方法可以在onTextChanged中改变文本时防止onTextChanged被调用?

1个回答

6
你可以使用标记来指定文本是否已经被更改过。如果它已经被更改过一次,那么就不要再次更改,否则进行更改。
int flag_text=0;
protected void onTextChanged(CharSequence text, int start,
    int lengthBefore, int lengthAfter) {

    if (flag_text==0) {
        flag_text=1;
        setText(tt);
    }
    super.onTextChanged(text, start, lengthBefore, lengthAfter);
}

1
这通常是我的做法,但如果有更优雅的解决方案,那将会很好。 - alex.zherdev
2
猜测您是想在setText(tt)之前加上"flag_text = 1"。 - BlueWanderer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接