当用户从自动完成建议中选择文本时,我想添加空间,因此当他继续键入时,他将从一个新词开始。

我尝试使用TextWatcher来做到这一点,但得到了IndexOutOfBoundsException

有什么建议?

我使用的文本查看器是:

    private class AddSpaceTextWatcher implements TextWatcher{

    boolean shouldAddSpace = false;

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

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (count - before > 1) // check that the new input is not from the keyboard
            shouldAddSpace = true;
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (shouldAddSpace) {
            shouldAddSpace = false;
            mAutoCompleteTextView.setText(" ");
        }
    }
}

我得到的异常(exception)是:
java.lang.IndexOutOfBoundsException: setSpan (18 ... 18) ends beyond length 1
        at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1018)
        at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:611)
        at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:607)
        at android.text.Selection.setSelection(Selection.java:76)
        at android.text.Selection.setSelection(Selection.java:87)
        at android.widget.EditText.setSelection(EditText.java:99)
        at android.widget.SearchView.setQuery(SearchView.java:1465)
        at android.widget.SearchView.onQueryRefine(SearchView.java:889)
        at android.widget.SuggestionsAdapter.onClick(SuggestionsAdapter.java:371)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19748)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

最佳答案

要选择多个项目,您可以简单地使用MultiAutoCompleteTextView,它是为此目的而专门构建的AutoCompleteTextView的子类。

或者

如果您只想在末尾添加一个空格,则只能选择一项,然后尝试以下操作:

public void afterTextChanged(Editable editable) {
    String text = editable.toString();
    if (shouldAddSpace && text.length() > 0 && !text.endsWith(" ")) {
        editable.append(' ');
    }
}

编辑:

附加空格后,您只需调用mAutoCompleteTextView.showDropDown();即可再次显示带有更新文本的下拉菜单。

10-08 08:16