validar tipos style studio propiedades mascara example edittext control android android-edittext android-textview

style - tipos de edittext android



Android-Manejar "Enter" en un EditText (20)

Me pregunto si hay una manera de manejar al usuario presionando Intro mientras escribe en un EditText , algo como el evento onSubmit HTML.

También me pregunto si hay una manera de manipular el teclado virtual de tal manera que el botón "Listo" esté etiquetado como otra cosa (por ejemplo, "Ir") y realice una determinada acción cuando se haga clic (de nuevo, como en Enviar).


Me pregunto si hay una manera de manejar al usuario presionando Intro mientras escribe en un Texto de Edición, algo como el evento onSubmit HTML.

Sí.

También me pregunto si hay una manera de manipular el teclado virtual de tal manera que el botón "Listo" esté etiquetado como otra cosa (por ejemplo, "Ir") y realice una determinada acción cuando se haga clic (de nuevo, como en Enviar).

Tambien si

android:imeOptions atributos de android:imeActionId y android:imeOptions , más el método setOnEditorActionListener() , todo en TextView .

Para cambiar el texto del botón "Listo" a una cadena personalizada, use:

mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);


Aquí hay una función estática simple que puede incluir en su clase de Utils o Keyboards que ejecutará el código cuando el usuario presione la tecla de retorno en un teclado de hardware o software. Es una versión modificada de la excelente respuesta de @ earlcasper.

/** * Return a TextView.OnEditorActionListener that will execute code when an enter is pressed on * the keyboard.<br> * <code> * myTextView.setOnEditorActionListener(Keyboards.onEnterEditorActionListener(new Runnable()->{ * Toast.makeText(context,"Enter Pressed",Toast.LENGTH_SHORT).show(); * })); * </code> * @param doOnEnter A Runnable for what to do when the user hits enter * @return the TextView.OnEditorActionListener */ public static TextView.OnEditorActionListener onEnterEditorActionListener(final Runnable doOnEnter){ return (__, actionId, event) -> { if (event==null) { if (actionId == EditorInfo.IME_ACTION_DONE) { // Capture soft enters in a singleLine EditText that is the last EditText. doOnEnter.run(); return true; } else if (actionId==EditorInfo.IME_ACTION_NEXT) { // Capture soft enters in other singleLine EditTexts doOnEnter.run(); return true; } else { return false; // Let system handle all other null KeyEvents } } else if (actionId==EditorInfo.IME_NULL) { // Capture most soft enters in multi-line EditTexts and all hard enters. // They supply a zero actionId and a valid KeyEvent rather than // a non-zero actionId and a null event like the previous cases. if (event.getAction()==KeyEvent.ACTION_DOWN) { // We capture the event when key is first pressed. return true; } else { doOnEnter.run(); return true; // We consume the event when the key is released. } } else { // We let the system handle it when the listener // is triggered by something that wasn''t an enter. return false; } }; }


En su xml, agregue el atributo imeOptions al editText

<EditText android:id="@+id/edittext_additem" ... android:imeOptions="actionDone" />

Luego, en su código Java, agregue OnEditorActionListener al mismo EditText

mAddItemEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(actionId == EditorInfo.IME_ACTION_DONE){ //do stuff return true; } return false; } });

Aquí está la explicación: imeOptions = actionDone asignará "actionDone" a la EnterKey. La tecla EnterKey en el teclado cambiará de "Enter" a "Done". Por lo tanto, cuando se presiona la tecla Intro, activará esta acción y, por lo tanto, la manejará.


Esta página describe exactamente cómo hacer esto.

https://developer.android.com/training/keyboard-input/style.html

Establezca android:imeOptions y verifique el actionId en onEditorAction. Entonces, si establece imeOptions en ''actionDone'', entonces buscará ''actionId == EditorInfo.IME_ACTION_DONE'' en onEditorAction. Además, asegúrese de configurar el android: inputType.

Aquí está el EditText del ejemplo vinculado anteriormente:

<EditText android:id="@+id/search" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/search_hint" android:inputType="text" android:imeOptions="actionSend" />

También puede establecer esto mediante programación utilizando la función setImeOptions(int) . Aquí está el OnEditorActionListener del ejemplo vinculado anteriormente:

EditText editText = (EditText) findViewById(R.id.search); editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { sendMessage(); handled = true; } return handled; } });


Esto debería funcionar

input.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if( -1 != input.getText().toString().indexOf( "/n" ) ){ input.setText("Enter was pressed!"); } } });


Esto es lo que haces. También está oculto en el código de muestra del desarrollador de Android ''Bluetooth Chat''. Reemplace las partes en negrita que dicen "ejemplo" con sus propias variables y métodos.

Primero, importe lo que necesita en la Actividad principal donde desea que el botón de retorno haga algo especial:

import android.view.inputmethod.EditorInfo; import android.widget.TextView; import android.view.KeyEvent;

Ahora, haga una variable de tipo TextView.OnEditorActionListener para su clave de retorno (aquí uso exampleListener );

TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener(){

Luego debe decirle al oyente dos cosas sobre qué hacer cuando se presiona el botón de retorno. Necesita saber de qué texto de edición estamos hablando (aquí uso exampleView ), y luego saber qué hacer cuando se presiona la tecla Intro (aquí, example_confirm () ). Si este es el último o el único texto de edición en su actividad, debería hacer lo mismo que el método onClick para su botón Enviar (o Aceptar, Confirmar, Enviar, Guardar, etc.).

public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { example_confirm();//match this behavior to your ''Send'' (or Confirm) button } return true; }

Finalmente, configure el oyente (lo más probable en su método onCreate);

exampleView.setOnEditorActionListener(exampleListener);


Esto funciona bien en los teléfonos LG Android. Impide que ENTER y otros caracteres especiales se interpreten como caracteres normales. Next botón Next o Done aparece automáticamente y ENTER funciona como se espera.

edit.setInputType(InputType.TYPE_CLASS_TEXT);


InputType en el campo de texto debe ser "text" para que funcione lo que CommonsWare dice. Solo probé todo esto, no hay inputType antes de la prueba y nada funcionó, Enter siguió registrando como soft ing. Después de inputType = texto, todo, incluido setImeLabel, funcionó.


Justo como un addendum a la respuesta de Chad (que funcionó casi perfectamente para mí), encontré que necesitaba agregar un cheque en el tipo de acción KeyEvent para evitar que mi código se ejecute dos veces (una vez en la tecla arriba y otra vez en la tecla abajo) evento).

if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { // your code here }

Consulte http://developer.android.com/reference/android/view/KeyEvent.html para obtener información sobre la repetición de eventos de acción (con la tecla Intro), etc.


La respuesta de Jared Law funciona como un encanto para mí.

Acabo de añadir estos depencendy:

import android.view.KeyEvent; import android.view.View; import android.widget.EditText;


Los teclados de hardware siempre producen eventos de entrada, pero los teclados de software devuelven diferentes ActionIDs y nulls en SingleLine EditTexts. Este código responde cada vez que el usuario presiona enter en un EditText al que se ha configurado este oyente, independientemente de EditText o del tipo de teclado.

import android.view.inputmethod.EditorInfo; import android.view.KeyEvent; import android.widget.TextView.OnEditorActionListener; listener=new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (event==null) { if (actionId==EditorInfo.IME_ACTION_DONE); // Capture soft enters in a singleLine EditText that is the last EditText. else if (actionId==EditorInfo.IME_ACTION_NEXT); // Capture soft enters in other singleLine EditTexts else return false; // Let system handle all other null KeyEvents } else if (actionId==EditorInfo.IME_NULL) { // Capture most soft enters in multi-line EditTexts and all hard enters. // They supply a zero actionId and a valid KeyEvent rather than // a non-zero actionId and a null event like the previous cases. if (event.getAction()==KeyEvent.ACTION_DOWN); // We capture the event when key is first pressed. else return true; // We consume the event when the key is released. } else return false; // We let the system handle it when the listener // is triggered by something that wasn''t an enter. // Code from this point on will execute whenever the user // presses enter in an attached view, regardless of position, // keyboard, or singleLine status. if (view==multiLineEditText) multiLineEditText.setText("You pressed enter"); if (view==singleLineEditText) singleLineEditText.setText("You pressed next"); if (view==lastSingleLineEditText) lastSingleLineEditText.setText("You pressed done"); return true; // Consume the event } };

La apariencia predeterminada de la tecla de entrada en singleLine = false da una flecha doblada para ingresar el teclado. Cuando singleLine = true en el último EditText la tecla dice DONE, y en EditTexts antes de que diga NEXT. De forma predeterminada, este comportamiento es consistente en todos los emuladores de vainilla, Android y Google. El atributo scrollHorizontal no hace ninguna diferencia. La prueba nula es importante porque la respuesta de los teléfonos a las entradas blandas se deja al fabricante e incluso en los emuladores, los emuladores de nivel 16 de vainilla responden a las entradas blandas largas y de edición horizontal de scroll.Horizontal con un id. el evento.


Primero, tienes que configurar EditarTexto escuchar la tecla presionando

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set the EditText listens to key press EditText edittextproductnumber = (EditText) findViewById(R.id.editTextproductnumber); edittextproductnumber.setOnKeyListener(this); }

En segundo lugar, defina el evento con la tecla presionada, por ejemplo, evento para configurar el texto de TextView:

@Override public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub // Listen to "Enter" key press if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { TextView textviewmessage = (TextView) findViewById(R.id.textViewmessage); textviewmessage.setText("You hit ''Enter'' key"); return true; } return false; }

Y, por último, no olvide importar EditText, TextView, OnKeyListener, KeyEvent en la parte superior:

import android.view.KeyEvent; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.TextView;


Sé que este tiene un año de antigüedad, pero acabo de descubrir que esto funciona perfectamente para un EditText.

EditText textin = (EditText) findViewById(R.id.editText1); textin.setInputType(InputType.TYPE_CLASS_TEXT);

Previene todo menos texto y espacio. No pude tabular, "devolver" ("/ n"), ni nada.


También puedes hacerlo ..

editText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { Log.i("event", "captured"); return false; } return false; } });


Tenía un propósito similar. Quería resolver presionando la tecla "Enter" en el teclado (que quería personalizar) en un AutocompletarTextView que extiende TextView. Probé diferentes soluciones desde arriba y parecían funcionar. PERO experimenté algunos problemas cuando cambié el tipo de entrada en mi dispositivo (Nexus 4 con ROM AOKP) desde SwiftKey 3 (donde funcionó perfectamente) al teclado estándar de Android (donde en lugar de manejar mi código del oyente, una nueva línea era ingresé después de presionar la tecla "Enter". Me tomó un tiempo manejar este problema, pero no sé si funcionará en todas las circunstancias, sin importar qué tipo de entrada use.

Así que aquí está mi solución:

Establezca el atributo de tipo de entrada de TextView en el xml en "texto":

android:inputType="text"

Personaliza la etiqueta de la tecla "Enter" en el teclado:

myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);

Establezca un OnEditorActionListener en el TextView:

myTextView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == KeyEvent.KEYCODE_ENTER) { // Handle pressing "Enter" key here handled = true; } return handled; } });

Espero que esto pueda ayudar a otros a evitar los problemas que tuve, porque casi me volvieron loco.


Una forma confiable de responder a un <enter> en un EditText es con un TextWatcher , un LocalBroadcastManager y un BroadcastReceiver . Debe agregar la biblioteca de soporte de v4 para usar LocalBroadcastManager. Uso el tutorial en vogella.com : 7.3 "Eventos de difusión local con LocalBroadcastManager" debido a su código conciso completo. En onTextChanged antes es el índice del final del cambio antes del cambio >; menos inicio. Cuando en el TextWatcher el subproceso de la interfaz de usuario está ocupado actualizando editable del editText, por lo tanto, enviamos una Intención para reactivar el BroadcastReceiver cuando el subproceso de la interfaz de usuario finaliza la actualización de editText.

import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.text.Editable; //in onCreate: editText.addTextChangedListener(new TextWatcher() { public void onTextChanged (CharSequence s, int start, int before, int count) { //check if exactly one char was added and it was an <enter> if (before==0 && count==1 && s.charAt(start)==''/n'') { Intent intent=new Intent("enter") Integer startInteger=new Integer(start); intent.putExtra("Start", startInteger.toString()); // Add data mySendBroadcast(intent); //in the BroadcastReceiver''s onReceive: int start=Integer.parseInt(intent.getStringExtra("Start")); editText.getText().replace(start, start+1,""); //remove the <enter> //respond to the <enter> here


funcionando perfectamente

public class MainActivity extends AppCompatActivity { TextView t; Button b; EditText e; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b = (Button) findViewById(R.id.b); e = (EditText) findViewById(R.id.e); e.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (before == 0 && count == 1 && s.charAt(start) == ''/n'') { b.performClick(); e.getText().replace(start, start + 1, ""); //remove the <enter> } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) {} }); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { b.setText("ok"); } }); }

}

funcionando perfectamente


password.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); submit.performClick(); return true; } return false; } });

Funciona muy bien para mi
Además ocultar teclado


editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) { // Action return true; } else { return false; } } });

Xml

<EditText android:id="@+id/editText2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/password" android:imeOptions="actionGo|flagNoFullscreen" android:inputType="textPassword" android:maxLines="1" />


final EditText edittext = (EditText) findViewById(R.id.edittext); edittext.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Perform action on key press Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show(); return true; } return false; } });