I would like to add space when the user select text from the auto complete suggestions, so when he continue to type he will start from a new word.
I tried to do it using TextWatcher
but I get IndexOutOfBoundsException
.
Any suggestions?
the text watcher I used is:
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(" ");
}
}
}
The exception I get is:
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)
For selecting multiple items, you can simply use MultiAutoCompleteTextView
which is a subclass of AutoCompleteTextView
specifically built for this purpose.
OR
If you just want to append a space at the end making only one item selectable than try this:
public void afterTextChanged(Editable editable) {
String text = editable.toString();
if (shouldAddSpace && text.length() > 0 && !text.endsWith(" ")) {
editable.append(' ');
}
}
Edit:
Once the space is appended, you can simply call mAutoCompleteTextView.showDropDown();
to bring up the drop down again with updated text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With