acostela
acostela

Reputation: 2727

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) {

        }
    });
}

Upvotes: 2

Views: 93

Answers (2)

Chandrakanth
Chandrakanth

Reputation: 3831

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);
            }

    }

Upvotes: 1

Arun Shankar
Arun Shankar

Reputation: 2295

Try using a textview with seteditable set as true. Set the min characters at "n" and keep the last "k" characters as editable. A custom textview would do the trick

Upvotes: 0

Related Questions