I wrote a form to check the region by phone number. Put the TextWatcher on the input form, it tracks the value of the input field and substitutes the mask, that's only if I delete the value and try to enter the number of another region, then another mask is substituted and an error occurs

java.lang.StackOverflowError at android.text.method.ReplacementTransformationMethod $ ReplacementCharSequence.getChars (ReplacementTransformationMethod.java:151)

It happens as I understand it because I try to assign two masks to EditText, the question is how do I delete the previous mask and replace it with a new one?

editPhone.addTextChangedListener(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) { if(editPhone.getText().toString().equals("+3")){ editPhone.addTextChangedListener(new MaskedWatcher("+38 (###) ###-##-##")); } if(editPhone.getText().toString().equals("+7")){ editPhone.addTextChangedListener(new MaskedWatcher("+7 (###) ###-##-##")); } if(editPhone.getText().toString().equals("")){ editPhone.setText("+"); editPhone.setSelection(editPhone.getText().length()); } if(editPhone.getText().toString().equals("+1")){ editPhone.addTextChangedListener(new MaskedWatcher("+1 (###) ###-##-##")); } } @Override public void afterTextChanged(Editable editable) { } }); 

    1 answer 1

    You have StackOverflowError due to the fact that you are on onTextChanged again setting TextWatcher for editPhone. You need to correct the logic in MaskedWatcher. So that inside this MaskedWatcher there was a check for the type of mask. and initially you need to editPhone.addTextChangedListener (new MaskedWatcher ()). Show the code new MaskedWatcher for a detailed answer.

    • github.com/VicMikhailau/MaskedEditText/tree/master/… , this is a third-party library - Heaven
    • Can globally create a mask and then set a new one through the setMask () method? - Heaven
    • Yes. You can make a successor of MaskedWatcher, with a constructor without a parameter. Or you can even use this MaskedWatcher with an arbitrary mask at the beginning. And on onTextChanged do setMask of the desired mask - pavel163
    • final MaskedWatcher maskedWatcher = new MaskedWatcher (""); maskedWatcher.setMask ("+ 38 (###) ### - ## - ##"); That's right, that's how it worked - Heaven