Skip to content

Instantly share code, notes, and snippets.

@rsicarelli
Last active December 19, 2015 04:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rsicarelli/5901016 to your computer and use it in GitHub Desktop.
Save rsicarelli/5901016 to your computer and use it in GitHub Desktop.
Component extends a EditText to create a mask for CPF (similar to Social Security Number in USA) in Android. Any comments please send me a private message. If you don't understand the comments in code (translating in some tradutor), let me know. Componente estendendo um EditText para uma máscara de CPF no Android. Alguma observação por favor me …
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayoutGitSicachester"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:focusableInTouchMode="true" >
<br.com.zaptaxi.motorista.components.CpfEditText
android:id="@+id/editTextCpf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/label_cpf"
android:inputType="number" />
</RelativeLayout>
/*
* Componente para um EditText personalizado com uma máscara. Qualquer comentário ou lógica diferente
* por favor e-mail me rodrigo.sicarelli@gmail.com
*
* @author sicachester
*/
package br.com.sicachester.components;
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 CpfEditText extends EditText {
private boolean isUpdating;
/*
* Mapeia o cursor para a posição que você quer o inteiro na tela + 1
* (+1 para o Padding funcionar. Se chegar no último caracter, e não ter um espaço vazio no próximo, irá travar).
* => 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
* # # # . # # # . # # # - # #
*/
private int positioning[] = { 0, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14};
public CpfEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public CpfEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public CpfEditText(Context context) {
super(context);
initialize();
}
public String getCleanText() {
String text = CpfEditText.this.getText().toString();
text.replaceAll("[^0-9]*", "");
return text;
}
private void initialize() {
//Número de caracteres na tela, contando os "." e "-" e sempre +1.
final int maxNumberLength = 14;
this.setKeyListener(keylistenerNumber);
//Seta o texto desejado na tela
this.setText(" . . - ");
this.setSelection(1);
this.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String current = s.toString();
/*
* Quando termina de preencher o número, seta como falso
* para não precisar ficar reprocessando o campo
*/
if (isUpdating) {
isUpdating = false;
return;
}
/* Retira qualquer caracter que não nos importa */
String number = current.replaceAll("[^0-9]*", "");
if (number.length() > 11)
number = number.substring(0, 11);
int length = number.length();
/* da um Pad no numero para 9 caracteres */
String paddedNumber = padNumber(number, maxNumberLength);
/* Corta a string do Cpf nas partes que nos interessam */
String part1 = paddedNumber.substring(0, 3);
String part2 = paddedNumber.substring(3, 6);
String part3 = paddedNumber.substring(6, 9);
String part4 = paddedNumber.substring(9, 11);
/* Cria a String para colocar na tela */
String cpf = part1 + "." + part2 + "." + part3 + "-" + part4 ;
/*
* Seta essa flag, então na proxima execução
* do afterTextChanged não ira fazer nada
*/
isUpdating = true;
CpfEditText.this.setText(cpf);
CpfEditText.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' };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment