EditText com mascara para telefone

935 views
Skip to first unread message

luciofm

unread,
Jun 22, 2011, 11:05:48 PM6/22/11
to androidb...@googlegroups.com
Opa,

Alguem já fez um EditText com mascara para numero de telefones, tipo (12) 3456-7890 e que esteja a fim de compartilhar a solução???

Obrigado...
Lúcio Maciel
luc...@gmail.com

luciofm

unread,
Jun 23, 2011, 8:26:47 AM6/23/11
to androidb...@googlegroups.com
Como sou impaciente não consegui esperar alguem responder..

É um hack, mas funciona legal...

package net.amdroid.test;

import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.widget.EditText;

public class PhoneEditText extends EditText {

private boolean isUpdating;

/* Maps the cursor position from phone number to masked number...
* 1234567890 => (12) 3456-7890 
*/
private int positioning[] = { 1, 2, 3, 6, 7, 8, 9, 11, 12, 13, 14 };

public PhoneEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}

public PhoneEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}

public PhoneEditText(Context context) {
super(context);
initialize();
}
 
public String getCleanText() {
String text = PhoneEditText.this.getText().toString();

text.replaceAll("[^0-9]*", "");
return text;
}

private void initialize() {

final int maxNumberLength = 10;
this.setKeyListener(keylistenerNumber);

this.setText("(  )     -    ");
this.setSelection(1);

this.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String current = s.toString();

/* Ok, here is the trick...
* calling setText below will recurse to this function,
* so we set a flag that we are actually updating the
* text, so we don't need to reprocess it...
*/
if (isUpdating) {
isUpdating = false;
return;
}

/* Strip any non numeric digit from the String... */
String number = current.replaceAll("[^0-9]*", "");
if (number.length() > 10)
number = number.substring(0, 10);
int length = number.length();

/* Pad the number to 10 characters... */
String  paddedNumber = padNumber(number, maxNumberLength);

/* Split phone number into parts... */
String ddd = paddedNumber.substring(0, 2);
String part1 = paddedNumber.substring(2, 6);
String part2 = paddedNumber.substring(6, 10);

/* build the masked phone number... */
String phone = "(" + ddd + ") " + part1 + "-" + part2;

/* Set the update flag, so the recurring call to afterTextChanged won't
* do nothing...
*/
isUpdating = true;
PhoneEditText.this.setText(phone);

PhoneEditText.this.setSelection(positioning[length]);
}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}

protected String padNumber(String number, int maxLength) {
String padded = new String(number);
for (int i = 0; i < maxLength - number.length(); i++)
padded += " ";
return padded;
}

private final KeylistenerNumber keylistenerNumber = new KeylistenerNumber();

private class KeylistenerNumber extends NumberKeyListener {

public int getInputType() {
return InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
}

@Override
protected char[] getAcceptedChars() {
return new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
}
}
}

Lúcio Maciel
luc...@gmail.com


2011/6/23 luciofm <luc...@gmail.com>

Neto

unread,
Jun 23, 2011, 8:52:45 AM6/23/11
to androidb...@googlegroups.com
Lúcio você tentou usar isso aqui android:inputType="phone"

2011/6/23 luciofm <luc...@gmail.com>



--
Notícias, reviews, tutoriais e tudo o que você queria saber sobre Android você encontra aqui
www.euandroid.com.br

@netolobo

luciofm

unread,
Jun 23, 2011, 9:04:36 AM6/23/11
to androidb...@googlegroups.com
Tentei, mas não funciona como eu preciso...

Da uma olhada na screenshot para ver como fica com esse meu edittext...


edittext.png


Lúcio Maciel
luc...@gmail.com
edittext.png

Thiago Lopes Rosa

unread,
Jun 23, 2011, 11:00:15 AM6/23/11
to androidb...@googlegroups.com
pq voce chamou de hack?
não é exatamente assim que deveria ser feito? =)



thiago

edittext.png

luciofm

unread,
Jun 23, 2011, 3:13:42 PM6/23/11
to androidb...@googlegroups.com
Não sei se essa é a forma mais elegante ou correta de corrigir o problema...

Aquele boolean isUpdating ficou feio pra caral...

Alem de ter ficado bem pouco flexível, sem possibilidade de configurar a mascara..

Foi um hack de poucos minutos para resolver um problema que eu tinha, mas com pouca flexibilidade...

Não sei tambem se o afterTextChanged é o melhor lugar para fazer essas alterações/validações...

Bom, mas o código está ai para quem quiser usar e melhorar...

Lúcio Maciel
luc...@gmail.com
edittext.png

Neto Lobo

unread,
Feb 27, 2013, 3:55:20 PM2/27/13
to androidb...@googlegroups.com
Ressucitando o tópico aqui, Lúcio como você aplicou essa máscara no seu EditText?


2011/6/23 luciofm <luc...@gmail.com>
edittext.png

luciofm

unread,
Feb 27, 2013, 4:11:38 PM2/27/13
to androidb...@googlegroups.com
Neto,

Era uma extensão do EditText,

então eu usava direto no xml

<net.amdroid.test.PhoneEditText>

Mas esse código não suporta o novo formato para numeros de são paulo.

Lúcio Maciel
luc...@gmail.com


2013/2/27 Neto Lobo <des...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

edittext.png

Neto Lobo

unread,
Feb 27, 2013, 4:27:03 PM2/27/13
to androidb...@googlegroups.com

Ah tah, entendi, minha intenção é modificar o código (máscara para número de celulares só). Obrigado pela resposta Lucio.

edittext.png

Wellington Gonçalves de Sousa

unread,
Nov 27, 2013, 9:44:17 AM11/27/13
to androidb...@googlegroups.com
Olá pessoal, estava precisando de uma mascara para Data, só que todos exemplos que encontrei não me atendia ou não funcionavam.
Vendo este exemplo do Lucio, decidi tentar modificá-la para data e deu certo, me atendeu. Com isso estou repassando para quem precisar:
 
 
Classe:
 
 

package

br.com.wellgsousa.pmixmonitor;



import

android.content.Context;



import

android.text.Editable;


 


import

android.text.InputType;



import

android.text.TextWatcher;


 


import

android.text.method.NumberKeyListener;



import

android.util.AttributeSet;


 


import

android.widget.EditText;



public

class DataEditText extends EditText {



       

private boolean isUpdating;


         



 


 


       

/* Maps the cursor position from date number to masked number...


        * 12122013 => 12/12/2013


         */


 


       

private int positioning[] = {0,1,3,4,6,7,8,9,10};


 



 


       

public DataEditText(Context context, AttributeSet attrs, int defStyle) {


 


               

super(context, attrs, defStyle);



                 initialize();


 


        }



 


 



       

public DataEditText(Context context, AttributeSet attrs) {


 


               

super(context, attrs);



                 initialize();


 


        }



 


 



       

public DataEditText(Context context) {



                 

super(context);


 


                initialize();



         }


 


 



         

public String getCleanText() {


 


                String text = DataEditText.

this.getText().toString();



 


 



                text.replaceAll(

"[^0-9]*", "");



                 

return text;


 


        }



 


 



       

private void initialize() {



 


 



               

final int maxNumberLength = 8;



               

this.setKeyListener(keylistenerNumber);


               


               

this.setText("  /  /    ");


 


               

this.setSelection(1);



               

this.addTextChangedListener(new TextWatcher() {



                         

public void afterTextChanged(Editable s) {


 


                                String current = s.toString();



 


 



                               

/* Ok, here is the trick...



                                 * calling setText below will recurse to this function,


 


                                * so we set a flag that we are actually updating the



                                 * text, so we don't need to reprocess it...


 


                                */



                                 

if (isUpdating) {


 


                                       

isUpdating = false;



                                         

return;


 


                                }



 


 



                               

/* Strip any non numeric digit from the String... */



                                String number = current.replaceAll(

"[^0-9]*", "");



                               

if (number.length() > 8)



                                         number = number.substring(0, 8);


 


                               

int length = number.length();



 


 



                               

/* Pad the number to 10 characters... */



                                 String  paddedNumber = padNumber(number, maxNumberLength);


 



 


 


                               

/* Split date number into parts... */


 


                                String dd = paddedNumber.substring(0, 2);



                                 String mm = paddedNumber.substring(2, 4);


 


                                String yyyy = paddedNumber.substring(4, 8);



                               

/* build the masked date number... */


                                 


                                 String date = dd +

"/" + mm + "/" + yyyy;



                               

/* Set the update flag, so the recurring call to afterTextChanged won't


 


                                * do nothing...



                                 */


 


                               

isUpdating = true;



                                DataEditText.

this.setText(date);



                                DataEditText.

this.setSelection(positioning[length]);


 


                        }


                         


                         



                       

public void beforeTextChanged(CharSequence s, int start, int count,


 


                                       

int after) {



                         }


 



 


 


                       

public void onTextChanged(CharSequence s, int start, int before,


 


                                       

int count) {



                         }


 


                });



         }


 



 


 


       

protected String padNumber(String number, int maxLength) {


 


                String padded =

new String(number);



                 

for (int i = 0; i < maxLength - number.length(); i++)


 


                        padded +=

" ";



                 

return padded;


 


        }



 


 



       

private final KeylistenerNumber keylistenerNumber = new KeylistenerNumber();


 



 


 


       

private class KeylistenerNumber extends NumberKeyListener {


 



 


 


               

public int getInputType() {


 


                       

return InputType.TYPE_CLASS_NUMBER



                                         | InputType.

TYPE_TEXT_FLAG_NO_SUGGESTIONS;


 


                }



 


 



               

@Override



                 

protected char[] getAcceptedChars() {


 


                       

return new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8','9' };



                 }


               


 


        }


       


       


}


E para usar, dentro do XML do Layout:
 

<

br.com.wellgsousa.pmixmonitor.DataEditText    


                                               

android:id="@+pm/contr_venc_bag_cilindro"


                                               

android:layout_width="160dp"                                            


                                               

android:layout_height="wrap_content"


                                               

android:textSize="18dp" />      


Marcelo Alves

unread,
Nov 27, 2013, 10:47:01 AM11/27/13
to androidb...@googlegroups.com

Legal!

Bota no GitHub, ou num Gist, mais fácil pra todo mundo pegar, e melhorar, caso precise :D

:: marcelo.alves

Santiago Rútales

unread,
Jan 15, 2014, 9:32:12 AM1/15/14
to androidb...@googlegroups.com
Isso reslve o 9o digito

if (current.matches("^(1)[1-9]{1}(9){1}(\\d{8})?$") ) {

                   
                    /* Split phone number into parts... */
                    ddd = paddedNumber.substring(0, 2);
                    part1 = paddedNumber.substring(2, 7);
                    part2 = paddedNumber.substring(7, 11).trim();
                   
                } else if (current.matches("^[2-9]{1}[1-9]{1}(\\d{8})?$")) {

                   
                    /* Split phone number into parts... */
                    ddd = paddedNumber.substring(0, 2);
                    part1 = paddedNumber.substring(2, 6);
                    part2 = paddedNumber.substring(6, 11).trim();

Jones Almeida

unread,
Jan 15, 2014, 10:23:37 AM1/15/14
to androidb...@googlegroups.com
public class CelularEditText extends EditText {

private class KeylistenerNumber extends NumberKeyListener {

@Override
protected char[] getAcceptedChars() {
return new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
}

@Override
public int getInputType() {
return InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
}
}

private boolean isUpdating;
private int FUltimoTamanho = 0;

private final KeylistenerNumber keylistenerNumber = new KeylistenerNumber();

private int positioning[] = { 1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 14 };



public CelularEditText(Context context) {
super(context);
initialize();
}

public CelularEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}

public CelularEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}

public String getCleanText() {
String text = CelularEditText.this.getText().toString();
text.replaceAll("[^0-9]*", "");
return text;
}

private void initialize() {

final int maxNumberLength = 11;
this.setKeyListener(keylistenerNumber);
this.setImeOptions(EditorInfo.IME_ACTION_NEXT);
this.setText("(  )      -     ");
this.setSelection(1);
this.addTextChangedListener(new TextWatcher() {

@Override
public void afterTextChanged(Editable s) {
String current = s.toString();
if (isUpdating) {
isUpdating = false;
return;
}
if (FUltimoTamanho>s.length()){
FUltimoTamanho = s.length();
return;
}
else
FUltimoTamanho = s.length();
String number = current.replaceAll("[^0-9]*", "").trim();
if (number.length() > maxNumberLength) 
number = number.substring(0, maxNumberLength);
int length = number.length();
String paddedNumber = padNumber(number, maxNumberLength);
String ddd = paddedNumber.substring(0, 2);
String part1 = paddedNumber.substring(2, 7);
String part2 = paddedNumber.substring(7, 11);
String phone = "(" + ddd + ")" + part1 + "-" + part2;
isUpdating = true;
CelularEditText.this.setText(phone);
CelularEditText.this.setSelection(positioning[length]);
}

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

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

protected String padNumber(String number, int maxLength) {
String padded = new String(number);
for (int i = 0; i < maxLength - number.length(); i++) 
padded += " ";
return padded;
}
}


2014/1/15 Santiago Rútales <santiag...@gmail.com>

--
Reply all
Reply to author
Forward
0 new messages