2

Estou tentando setar automaticamente uma mascara ao campo, não conheço alguma outra forma de fazer, estou fazendo assim:

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

E não esta funcionando, existe alguma forma de fazer isto ?

Esta sendo setado quando o focus do campo esta saindo. Conforme a indicação de uma resposta fiz a atualização porém continua dar alguns problemas diferenciados.

Tenho a classe MASK que está assim:

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

}

E quando faço o evento estou fazendo assim:

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

LOG ERROS

  1. QUANDO DIGITO PELA PRIMEIRA VEZ ELE NÃO ESTA PEGANDO AUTOMATICAMENTE A MASCARA
  2. DEPENDENDO DE COMO EU FAÇO ELE BLOQUEIA O APLICATIVO E TRAVA, SEM APARECER NENHUM LOG DE ERRO. ISTO ACONTESCE QUANDO VOU NO TELEFONE DIGITO, DEPOIS CLICO NO CELULAR DIGITO, APAGO CELULAR E DIGITO QUANDO VOU APAGAR O TELEFONE ELE TRAVA

2 Respostas 2

4

Fala Renan,

É bem mais simples do que você acha, olha esse exemplo:

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

Pronto, a máscara está feita.

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

Segue o código da classe Mask:

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

}
10
  • Fiz uma edição na minha resposta com o código da classe 15/05/2017 às 18:01
  • Se você não é o autor desse código deve fazer referência a onde foi copiá-lo.
    – ramaral
    15/05/2017 às 18:07
  • Basta incluir mais um #, ficando dessa forma "(##)#####-####" 15/05/2017 às 18:15
  • @LeonardoDias estou tendo problemas com seu produto, porque so esta funcionando quando altero o campo 16/05/2017 às 12:16
  • Tipo a primeira vez que digito não pega a mascara 16/05/2017 às 12:16
1

Criei uma extensão em Kotlin do TextWatcher que resolve esse problema. Funciona para números nos dois formatos brasileiros: (XX) XXXX XXXX and (XX) XXXXX XXXX.

Segue o link: https://gist.github.com/kvdesa/113ef4ababc1aab19e55551b91aa9f37

Exemplo de uso:

    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)
2
  • Kevin, mto bom a sua classe, gostei dela e até peço permissão para com base nela criar algumas soluções para problemas aqui do dia-a-dia! Vlw grande abraço! 4/09/2019 às 0:35
  • @EduardoRafaelMoraes, sem problemas!
    – Kévin
    5/09/2019 às 8:10

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .