Setando mask android phone field

Asked

Viewed 4,903 times

2

I’m trying to automatically set a mask to the field, I don’t know any other way to do it, I’m doing it like this:

if(s.equals('(')){
    edtCelular.setText(texto);
}else{
    texto = "(" + telefone.substring(0, 2) + ") " + telefone.substring(2, 7) + "-" + telefone.substring(7, 11);
    edtCelular.setText(texto);
}

And it’s not working, there’s some way to do this ?

It’s being set when the field’s phocus is leaving. According to the indication of an answer I made the update but it continues to give some differentiated problems.

I have the class MASK that is like:

package com.fomedemais.FomeDemais;

 import android.text.Editable;
 import android.text.TextWatcher;
 import android.widget.EditText;

public class Mask {

public static String unmask(String s) {
    return s.replaceAll("[.]", "").replaceAll("[-]", "")
            .replaceAll("[/]", "").replaceAll("[(]", "")
            .replaceAll("[)]", "");
}

public static TextWatcher insert(final String mask, final EditText ediTxt) {
    return new TextWatcher() {
        boolean isUpdating;
        String old = "";
        public void onTextChanged(CharSequence s, int start, int before,int count) {
            String str = Mask.unmask(s.toString());
            String mascara = "";
            if (isUpdating) {
                old = str;
                isUpdating = false;
                return;
            }
            int i = 0;
            for (char m : mask.toCharArray()) {
                if (m != '#' && str.length() > old.length()) {
                    mascara += m;
                    continue;
                }
                try {
                    mascara += str.charAt(i);
                } catch (Exception e) {
                    break;
                }
                i++;
            }
            isUpdating = true;
            ediTxt.setText(mascara);
            ediTxt.setSelection(mascara.length());
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void afterTextChanged(Editable s) {}
    };
 }

}

And when I do the event I’m doing so:

@FocusChange(R.id.edtTelefone)
void focusAlterado(View v, boolean hasFocus) {
    if(!hasFocus){
        edtTelefone.addTextChangedListener(Mask.insert("(##)####-####", edtTelefone));
    }
}

LOG ERRORS

  1. WHEN I TYPE FOR THE FIRST TIME HE’S NOT AUTOMATICALLY TAKING THE MASK
  2. Depending on how I do it blocks the application and crashes, no error log appears. THIS HAPPENS WHEN I GO ON THE PHONE DIGITO, THEN CLICK ON THE PHONE DIGITO, DELETE CELL PHONE AND TYPE WHEN I WILL ERASE THE PHONE IT LOCKS

2 answers

4


Fala Renan,

It’s much simpler than you think, look at this example:

id_do_campo.addTextChangedListener(Mask.insert("(##)####-####", id_do_campo));

Okay, the mask is made.

------------ Edit:

Follows the code of the Mask class:

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class Mask {

    public static String unmask(String s) {
        return s.replaceAll("[.]", "").replaceAll("[-]", "")
                .replaceAll("[/]", "").replaceAll("[(]", "")
                .replaceAll("[)]", "");
    }

    public static TextWatcher insert(final String mask, final EditText ediTxt) {
        return new TextWatcher() {
            boolean isUpdating;
            String old = "";
            public void onTextChanged(CharSequence s, int start, int before,int count) {
                String str = Mask.unmask(s.toString());
                String mascara = "";
                if (isUpdating) {
                    old = str;
                    isUpdating = false;
                    return;
                }
                int i = 0;
                for (char m : mask.toCharArray()) {
                    if (m != '#' && str.length() > old.length()) {
                        mascara += m;
                        continue;
                    }
                    try {
                        mascara += str.charAt(i);
                    } catch (Exception e) {
                        break;
                    }
                    i++;
                }
                isUpdating = true;
                ediTxt.setText(mascara);
                ediTxt.setSelection(mascara.length());
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            public void afterTextChanged(Editable s) {}
        };
    }

}
  • I made an edit on my reply with the class code

  • If you are not the author of this code you should reference where you copied it.

  • Just include one more #, staying that way "(##)#####-####"

  • @Leonardodias I’m having problems with your product, because it’s only working when I change the field

  • Like the first time I type doesn’t catch the mask

  • It has to work as you type in the phone numbers, that’s not it?

  • no, only when I edit

  • I think this in this onTextChanged method is not working.

  • Another thing, depending on how I do, the app hangs

  • I took the acceptance of the question to make a review

Show 5 more comments

1

I created an extension in Kotlin from Textwatcher that solves this problem. Works for numbers in both Brazilian formats: (XX) XXXX XXXX and (XX) XXXXX XXXX.

Follow the link: https://gist.github.com/kvdesa/113ef4ababc1aab19e55551b91aa9f37

Example of use:

    val editText: EditText() // The field you want to be formatted
    val country = PhoneNumberFormatType.EN_US // OR PhoneNumberFormatType.PT_BR
    val phoneFormatter = PhoneNumberFormatter(WeakReference(editText), country)
    editText.addTextChangedListener(phoneFormatter)
  • Kevin, I’m good in your class, I liked it and I even ask permission to create some solutions to problems here day-to-day! Vlw big hug!

  • @Eduardorafaelmoraes, without problems!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.