-5

I have an EditText and I want to format the whatever numbers are entered in the EditText into the US phone number format such as 1(123)123-123 so if the user enters the digit 1 automatically ( will be added this should work for deleting as well. I was able to add a text watcher and set up the logic but I am getting messed up during handling the deletion case.

Here is my code logic to format the first bracket but if we delete the bracket then it wont work

editText.addTextChangedListener(new TextWatcher() {
        public int after;
        public int before;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            before = count;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            after = count;

        }

        @Override
        public void afterTextChanged(Editable s) {
            editText.removeTextChangedListener(this);
            if (before < after) {
                if (s.length() == 4 && s.charAt(0) == '1') {
                    String formated = "1 (" + s.toString().substring(1, 4) + ")";
                    editText.setText(formated);
                    editText.setSelection(editText.getText().toString().length());
                }
            }

            editText.addTextChangedListener(this);
        }
    });

1 Answers1

0

I wouldn't use this functionality to check if the text was changed:

if (before < after)

Just given the case someone uses copy-paste to replace the phone number or marks one digit before replacing it. Better save your text somewhere and if !oldtext.equals(s.toString()) continue.

Assuming editText is your Textbox. Code is also untested, use at your own risk.

    public void afterTextChanged(Editable s) {
                editText.removeTextChangedListener(this);
                if (before < after) {
                    if (s.length() == 4 && s.charAt(0) == '1') {
                        long phoneFmt = Long.parseLong(s.toString().replaceAll("[^\\d]", ""),10);

DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
String phoneRawString= phoneDecimalFmt.format(phoneFmt);

java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
    //suposing a grouping of 3-3-4
String[] phoneNumArr={phoneRawString.substring(0, 3),
          phoneRawString.substring(3,6),
          phoneRawString.substring(6)};


                        editText.setText(phoneMsgFmt.format(phoneNumArr));
                        editText.setSelection(editText.getText().toString().length());
                    }
                }

                editText.addTextChangedListener(this);
            }
Qohelet
  • 1,459
  • 4
  • 24
  • 41