alcatrazbr
1/13/2017 - 5:38 PM

Mask mascara

Mask mascara

package br.com.xqx.alcatraz.motokkascli.apoio;

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

/**
 * Created by alcatraz on 10/01/2017.
 */

public class Mask {

        public static String unmask(String s) {
            return s.replaceAll("[.]", "").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;
                    if( str.length() > old.length()){
                        for (char m : mask.toCharArray()) {
                            if (m != '#') {
                                mascara += m;
                                continue;
                            }else{
                                try {
                                    mascara += str.charAt(i);
                                } catch (Exception e) {
                                    break;
                                }
                                i++;
                            }
                        }
                    }else{
                        mascara = s.toString();
                    }

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


TextWatcher edtTelefoneIndicacaoMask;
edtTelefoneIndicacaoMask = Mask.insert("(##) #####-####", edtIndicacaoTel);
edtIndicacaoTel.addTextChangedListener(edtTelefoneIndicacaoMask);