I wonder if it is possible to have a phone mask in a text View

Asked

Viewed 1,405 times

2

I would like to know how to have a phone mask in a text View field.

In my case I have a listview with contacts where in each line of this listview appears the name of the contact and the phone.

I’d like the phone to have the mask (##)####-####.

Remembering that in customer registration the mask already works.

Thanks in advance to those who, anyway, can help in a clear and specific way because I do not have much experience. Thank you.

My client registration code:

 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.DialogInterface;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import br.gestaoBd.BancoDeDados.ClienteDao;
 import br.gestaoBd.Beans.Cliente;

 public class CadCliente extends Activity {

EditText edId, edNome, edEmail, edTelefone, edEndereco, edCpf, edRg;
ClienteDao cliDao;

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.cad_clientes);
    edId = (EditText) findViewById(R.id.cadEdId);
    edNome = (EditText) findViewById(R.id.cadEdNome);
    edEmail = (EditText) findViewById(R.id.cadEdEmail);
    edTelefone = (EditText) findViewById(R.id.cadEdTelefone);
    edTelefone.addTextChangedListener(Mask.insert("(##)####-####", edTelefone));
    edEndereco = (EditText) findViewById(R.id.cadEdEndereco);
    edCpf = (EditText) findViewById(R.id.cadEdCpf);
    edCpf.addTextChangedListener(Mask.insert("###.###.###-##", edCpf));
    edRg = (EditText) findViewById(R.id.cadEdRg);
    edRg.addTextChangedListener(Mask.insert("##.###.###-#", edRg));

    Cliente clienteRecebido = (Cliente) getIntent().getSerializableExtra("Cliente");
    if (clienteRecebido != null) {
        montaTela(clienteRecebido);
    } else {
        montaTela(new Cliente());
    }

    Button btnSalvar = (Button) findViewById(R.id.btSalvar);
    btnSalvar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Cliente cli = new Cliente();
            cli.setId(Integer.valueOf(edId.getText().toString()));
            cli.setNome(edNome.getText().toString());
            cli.setEmail(edEmail.getText().toString());
            cli.setTelefone(Mask.unmask(edTelefone.getText().toString()));
            cli.setEndereco(edEndereco.getText().toString());
            cli.setRg(Mask.unmask(edRg.getText().toString()));
            cli.setCpf(Mask.unmask(edCpf.getText().toString()));

            if (cli.getNome().equals("")) {
                edNome.setError("Preencha o nome");
                return;

            } else if (cli.getEmail().equals("")) {
                edEmail.setError("Preencha o Email");
                return; 

            } else if (cli.getTelefone().equals("")) {
                edTelefone.setError("Preencha o telefone");
                return; 

            } else if (cli.getEndereco().equals("")) {
                edEndereco.setError("Preencha o endereço");
                return; 

            } else if (cli.getRg().equals("")) {
                edRg.setError("Preencha o RG");
                return; 

            } else if (cli.getCpf().equals("")) {
                edCpf.setError("Preencha o CPF"); 
                return; 
            }

            if (cli.getId() > 0) {
                getCliDao().alterar(cli);
                ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                        ToastManager.INFORMATION);
            } else {
                getCliDao().inserirCliente(cli);
                ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                        ToastManager.INFORMATION);
            }
        }

    }
    );

    Button btnLimpar = (Button) findViewById(R.id.btLimpar);

    btnLimpar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            montaTela(new Cliente());
        }
    }
    );

    Button btExcluir = (Button) findViewById(R.id.btExcluir);
    btExcluir.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final Cliente cli = new Cliente();
            cli.setId(Integer.valueOf(edId.getText().toString()));
            cli.setNome(edNome.getText().toString());
            cli.setEmail(edEmail.getText().toString());
            cli.setTelefone(edTelefone.getText().toString());
            cli.setEndereco(edEndereco.getText().toString());
            cli.setRg(edRg.getText().toString());
            cli.setCpf(edCpf.getText().toString());
            AlertDialog.Builder builder = new AlertDialog.Builder(CadCliente.this);
            builder.setTitle("Deseja Excluir?");
            builder.setMessage("O Cliente será deletado!");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    getCliDao().excluir(cli);
                    montaTela(new Cliente());
                    ToastManager.show(getBaseContext(), "Cliente excluído",
                            ToastManager.INFORMATION);

                }

            });

            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    ToastManager.show(getBaseContext(), "Cancelado",
                            ToastManager.INFORMATION);
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        }
    });

}

private void montaTela(Cliente cliente) {
    edId.setText(String.valueOf(cliente.getId()));
    edNome.setText(cliente.getNome());
    edEmail.setText(cliente.getEmail());
    edTelefone.setText(cliente.getTelefone());
    edEndereco.setText(cliente.getEndereco());
    edCpf.setText(cliente.getCpf());
    edRg.setText(cliente.getRg());

}

public ClienteDao getCliDao() {
    if (cliDao == null) {
        cliDao = new ClienteDao();
    }
    return cliDao;
}

}

My Customer Adapter:

 import android.content.Context;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.ImageView;
 import android.widget.TextView;
 import br.gestaoBd.Beans.Cliente;
 import br.gestaoBd.Mask;
 import br.gestaoBd.R;
 import java.util.List;

 public class ClienteAdapter extends BaseAdapter {  

private Context context;
private List<Cliente> clientes;

public ClienteAdapter(Context context, List<Cliente> clientes) {
    this.context = context;
    this.clientes = clientes;
}

public int getCount() {
    return clientes.size();
}

public Object getItem(int position) {
    return clientes.get(position);
}

public long getItemId(int position) {
    return clientes.get(position).getId();
}  


public View getView(int position, View convertView, ViewGroup parent) {
    Cliente cliente = clientes.get(position);

    LayoutInflater layout = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = layout.inflate(R.layout.linhacli, null);

    Log.i("AULA", "Montou:" + cliente.getNome());
    Log.e("ERRO", "Valor da variavel estava nullo!");

    ImageView imgImageView = (ImageView) view.findViewById(R.id.imageView1);
    imgImageView.setImageResource(R.drawable.sem_foto);

    TextView edNome = (TextView) view.findViewById(R.id.textView1);
    edNome.setText(cliente.getNome());

    TextView lblTelefone = (TextView) view.findViewById(R.id.textView2);
    lblTelefone.setText(cliente.getTelefone());



    return view;
}
}

My List of Clients;

 import static android.R.id.list;
 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ListView;
 import br.gestaoBd.BancoDeDados.ClienteDao;
 import br.gestaoBd.Beans.Cliente;
 import br.gestaoBd.listaadapters.ClienteAdapter;
 import java.util.ArrayList;
 import java.util.Collections;


 public class ListClientes extends Activity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

ListView lista;
ArrayList<Cliente> clientes;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_clientes);

    lista = (ListView) findViewById(R.id.listview);

    lista.setOnItemLongClickListener(this);
    lista.setOnItemClickListener(this);


    atualizar(null);
}

public void atualizar(View view) {
    ClienteDao cliDao = new ClienteDao();

    clientes = cliDao.getListagem();
    lista.setAdapter(new ClienteAdapter(getBaseContext(), clientes));

}

public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Intent cadClienteIntent = new Intent(this, CadCliente.class);
    cadClienteIntent.putExtra("Cliente", clientes.get(position));
    startActivity(cadClienteIntent);
    return true;
}

public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    Intent cadPedidoIntent = new Intent(this, CadPedido.class);
    cadPedidoIntent.putExtra("Cliente", clientes.get(position));
    startActivity(cadPedidoIntent);

}

}

1 answer

6


For this, let’s do just like TextView.

But instead of going through one changeListener, let’s move on to String ready-made!

In your class Mask,implement the following method:

  public static String addMask(final String textoAFormatar, final String mask){
        String formatado = "";
        int i = 0; 
        // vamos iterar a mascara, para descobrir quais caracteres vamos adicionar e quando...
        for (char m : mask.toCharArray()) { 
            if (m != '#') { // se não for um #, vamos colocar o caracter informado na máscara 
                formatado += m;
                continue; 
            }
            // Senão colocamos o valor que será formatado
            try {
                formatado += textoAFormatar.charAt(i);
            } catch (Exception e) {
                break;
            }
            i++;
        }
        return formatado;
    }

On your customer Adapter:

  TextView lblTelefone = (TextView) view.findViewById(R.id.textView2);
   lblTelefone.setText(Mask.addMask(cliente.getTelefone(), "(##)####-####"));
  • 1

    Perfect! @Thiago Luiz Domacoski . Thank you very much

Browser other questions tagged

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