Formato Editar vista de texto para los números de teléfono
Tengo una vista EditText y quiero que el formato de la entrada del usuario en el formato de número de teléfono. Por ejemplo, cuando el usuario escribe en 1234567890, la vista EditText debería mostrarlo dinámicamente como "(123) 456-7890" tan pronto como se introducen los 3 primeros números.
He intentado lo siguiente en mi OnCreate, pero no parecía hacer nada para mí …
- Intercepción de llamadas en android
- Comparación de números de teléfono en Android
- Recuperar un número de teléfono con ContactsContract en Android: la función no funciona
- Android: ¿Cómo obtener la identificación de contacto por el número de teléfono?
- Android: cómo formateo el número como teléfono con paréntesis
EditText ET = (EditText) findViewById(R.id.add_number); ET.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
¿Cómo puedo obtener la entrada del usuario para que aparezca en el formato de número de teléfono?
- Cómo obtener el número de teléfono mediante el registro de llamadas de android?
- ¿Cómo utilizo AsYouTypeFormatter TextWatcher en la aplicación de Android?
- Android: recuperar el nombre del contacto desde el número de teléfono
- Utilizar autocompletar texto con número de teléfono de contactos
- Cómo obtener la etiqueta localizada de los tipos de teléfono?
- ¿Cómo puedo abrir el marcador para que se muestre el número de teléfono?
- Bloquear SMS salientes por contentObserver
- No se ha encontrado actividad para manejar la acción intencional.
Con este código puede hacer un TextWatcher personalizado y hacer cualquier formato que desee:
ET.addTextChangedListener(new PhoneNumberFormattingTextWatcher() { //we need to know if the user is erasing or inputing some new character private boolean backspacingFlag = false; //we need to block the :afterTextChanges method to be called again after we just replaced the EditText text private boolean editedFlag = false; //we need to mark the cursor position and restore it after the edition private int cursorComplement; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { //we store the cursor local relative to the end of the string in the EditText before the edition cursorComplement = s.length()-ET.getSelectionStart(); //we check if the user ir inputing or erasing a character if (count > after) { backspacingFlag = true; } else { backspacingFlag = false; } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // nothing to do here =D } @Override public void afterTextChanged(Editable s) { String string = s.toString(); //what matters are the phone digits beneath the mask, so we always work with a raw string with only digits String phone = string.replaceAll("[^\\d]", ""); //if the text was just edited, :afterTextChanged is called another time... so we need to verify the flag of edition //if the flag is false, this is a original user-typed entry. so we go on and do some magic if (!editedFlag) { //we start verifying the worst case, many characters mask need to be added //example: 999999999 <- 6+ digits already typed // masked: (999) 999-999 if (phone.length() >= 6 && !backspacingFlag) { //we will edit. next call on this textWatcher will be ignored editedFlag = true; //here is the core. we substring the raw digits and add the mask as convenient String ans = "(" + phone.substring(0, 3) + ") " + phone.substring(3,6) + "-" + phone.substring(6); ET.setText(ans); //we deliver the cursor to its original position relative to the end of the string ET.setSelection(ET.getText().length()-cursorComplement); //we end at the most simple case, when just one character mask is needed //example: 99999 <- 3+ digits already typed // masked: (999) 99 } else if (phone.length() >= 3 && !backspacingFlag) { editedFlag = true; String ans = "(" +phone.substring(0, 3) + ") " + phone.substring(3); ET.setText(ans); ET.setSelection(ET.getText().length()-cursorComplement); } // We just edited the field, ignoring this cicle of the watcher and getting ready for the next } else { editedFlag = false; } } });
Asegúrese de limitar la duración de EditText en XML a 14 caracteres
<EditText android:id="@+id/editText_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:lines="1" android:maxLength="14"/>
Hice una combinación de cosas, modifiqué mi tipo de entrada al teléfono, luego utilicé regex para eliminar todos los caracteres no numéricos: phonenumber = phonenumber.replaceAll ("\ D", "");
Paso 1: Aquí el código para el campo de entrada en el archivo XML.
<EditText android:id="@+id/editText_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:lines="1" android:maxLength="14"/>
Paso 2: Aquí está el código agregado en MainFile.java
phoneNo = (EditText)findViewById(R.id.editText_phone); phoneNo.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
Salida: le dará el número como (123) 456-7890
En su diseño, ajuste el modo de entrada a "teléfono"
http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputMethod http://developer.android.com/reference/android/text/InputType.html#TYPE_CLASS_PHONE
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="phone" />
Si esto no satisface exactamente sus necesidades, añada un oyente a su EditText y formatee el texto manualmente en cada golpe de tecla.
editText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { // format your EditText here } return false; } });
Prueba esto
El método PhoneNumberFormattingTextWatcher () no estaba funcionando i tried allot finally i get las soluciones
-
En su archivo xml, pegue este
<EditText android:id="@+id/editTextId" android:layout_height="wrap_content" android:layout_width="match_parent" android:inputType="phone" android:digits="0123456789+" />
-
En su método de oncreate pegar este
final EditText editText = (EditText) findViewById(R.id.editTextId); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { String text = editText.getText().toString(); int textLength = editText.getText().length(); if (text.endsWith("-") || text.endsWith(" ") || text.endsWith(" ")) return; if (textLength == 1) { if (!text.contains("(")) { editText.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString()); editText.setSelection(editText.getText().length()); } } else if (textLength == 5) { if (!text.contains(")")) { editText.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString()); editText.setSelection(editText.getText().length()); } } else if (textLength == 6) { editText.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString()); editText.setSelection(editText.getText().length()); } else if (textLength == 10) { if (!text.contains("-")) { editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString()); editText.setSelection(editText.getText().length()); } } else if (textLength == 15) { if (text.contains("-")) { editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString()); editText.setSelection(editText.getText().length()); } } else if (textLength == 18) { if (text.contains("-")) { editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString()); editText.setSelection(editText.getText().length()); } } } });
SALIDA : –
En tu código Java puedes usar
yourEditText.setInputType(InputTytpe.TYPE_CLASS_PHONE)
O en su xml
android:inputType="phone"
Java
XML
Podrías hacer esto con JQuery validate (onkeyup event) para que pudieras hacer el formato dinámico mientras escriben (con una experiencia de jarring allí para contemplar) – o podrías hacerlo con una biblioteca MVVM como RAZOR o KnockoutJS (al salir del campo) .
Ejemplos de lo que desea hacer están tanto en el sitio de documentación de JQuery Validate como en el sitio de JS de knockout.
- Android – constantes de tipo sms
- ¿Es una buena idea llamar a finish () después de iniciar una nueva Actividad en Android?