Search code examples
javaandroidmultiautocompletetextviewandroid-textwatcher

Enter double space to replace comma in multiautocompletetextview


I want to add comma when I enter double space from keyboard in multiautocompletetextview. I search lots of thing in google. But can't reach my goal. I want to replace comma for double space entering by user.

So obviously, I must have to write something logic in ontextChange() or OnAfterTextChanged() in addtextwatcher listener.but i do't got event of after add 2 space.

I have already used comma tokenizer when select word from list.but i want to add comma when user entering double space using keypad.

Thanks in advance


Solution

  • The simplest solution i can provide you is to use String.replace(), Here is small code snippet to help you

     @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        ...
    
        edt.addTextChangedListener(textWatcher);
    }
    

    And TextWatcher which you are going to set on EditText

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            edt.removeTextChangedListener(textWatcher);
            String text = edt.getText().toString();
            text = text.replace("  ", ",");
            edt.setText(text);
            edt.setSelection(text.length());
            edt.addTextChangedListener(textWatcher);
        }
    
        @Override
        public void afterTextChanged(Editable editable) {
    
        }
    };
    

    enter image description here