当用户从自动完成建议中选择文本时,我希望加入空格,这样当用户继续输入时,他将从一个新单词开始。
我尝试使用 TextWatcher
来实现它,但是我遇到了 IndexOutOfBoundsException
。
有什么建议吗?
我使用的 TextWatcher 是:
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(" ");
}
}
}
我得到的异常是:
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)