Search code examples
androidandroid-edittexttextwatcher

remove fixed number of digits


Maybe this is not so hard for you but I need some help. I have and editText that shows a code of 6 digits length. e.g. "292000", "123000", etc...

I have this info in an editText I would like that the user only can remove the last 2 digits to put their own number (they can only change the last two digits). e.g. "292020" "123001".

I'm using textwatchers but I can't use setText inside it because I'll get a stackoverflow error. Any help will be so appreciated.

codArt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(codArt.getSelectionStart() < 5) {
                codArt.setText(charSequence);
                codArt.setSelection(5);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
}

Solution

  • Remove code from onTextChanged() method and try like below...

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.length() == 4 && after == 0) {
                    codArt.removeTextChangedListener(this);
                    codArt.setText(s);
                    codArt.setSelection(s.length());
                    codArt.addTextChangedListener(this);
                }
    
        }