在AutoCompleteTextView中覆盖Backspace的默认行为

5

我正在使用AutoCompleteTextView,回退按钮的默认行为如下。

比如我输入“Ar”,这会给我一个建议“Argentina”,我从下拉菜单中选择“Argentina”…文本现在变成了“Argentina ”。但是,如果我需要删除最后一个字符,我按键盘上的退格键,AutcompleteTextView会删除所有文本直到我输入的位置(即文本现在再次变为“Ar”)。

如何消除此行为并使AutoComplete中的文本正常工作?

起初,我以为它是某种SpannableString,所以我调用了“clearSpans()”,但似乎不起作用。有什么指导吗?

提前致谢。

2个回答

1
我认为你正在使用 MultiAutoCompleteTextView 并添加了 setTokenizer(new SpaceTokenizer())。如果你使用 AutoCompleteTextView 而不是 MultiAutoCompleteTextView,并移除 setTokenizer(...),问题将会消失。

0

我没有找到任何解决方案,但最终我想出了一个方法,这段代码对我有用:

editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                // removing QwertyKeyListener.Replaced span
                Editable text = editText.getText();
                Object[] spans = text.getSpans(0, text.length(), Object.class);
                if (spans != null) {
                    for (int i = spans.length - 1; i >= 0; i--) {
                        Object o = spans[i];
                        String desc = "" + o; // This is a hack, not a perfect solution, but works. "QwertyKeyListener.Replaced" is a private type
                        if (desc.indexOf("QwertyKeyListener$Replaced") != -1) {
                            text.removeSpan(o);
                        }
                    }
                }
            } catch (Throwable e) {
                MyUtil.msgError(e);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

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