Search code examples
javaandroidandroid-edittext

Text deletion in EditText stops because of setSelection()


I'd like to highlight some words in my EditText with the following code:

mEditText.addTextChangedListener(new TextWatcher() {
        private boolean ignoreChange = false;
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            int cursorPosition = mEditText.getSelectionStart();
            if(!ignoreChange){
                //Highlight words
                ignoreChange = true;
                mEditText.setText(spannable);
                mEditText.setSelection(cursorPosition);
                ignoreChange = false;
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

So, there are two problems:

-While I am touching delete button on the keyboard, it deletes only one char instead of deleting all chars till I am touching the button.

-The text input is very slow.

Both problems as I see occur because of setSelection(..). I use setSelection(..) because setText(..) sends cursor to the begining of EditText.


Solution

  • So, the solution for the problem was put the code from onTextChanged(...) method into afterTextChanged(...). This way we can edit EditText's text straight via editable object, so we don't need to call mEditText.setText(...) and mEditText.setSelection(...)