Android-Manejar "Enter" en un EditText


Me pregunto si hay una manera de manejar al usuario presionando Enter mientras escribe un EditText, algo así como el evento HTML onubmit.

También se preguntan si hay una manera de manipular el teclado virtual de tal manera que el botón "Hecho" es la etiqueta algo más (por ejemplo, "Ir"), y realiza una determinada acción cuando se hace clic (de nuevo, como onSubmit).

Author: MiguelHincapieC, 2009-09-29

20 answers

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

Sí.

También se pregunta si hay una manera de manipular el teclado virtual en de tal manera que el botón "Hecho" es etiquetado algo más (por ejemplo "Go") y realiza una determinada acción cuando se hace clic (de nuevo, como onSubmit).

También sí.

Usted querrá mirar en el android:imeActionId y android:imeOptions atributos, además de la setOnEditorActionListener() método, todos en TextView.

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

mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
 334
Author: CommonsWare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-08 15:05:00

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

Primero, importa lo que necesites en la actividad principal donde quieres 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í utilizo exampleListener);

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

Entonces tienes que decirle a la escucha dos cosas sobre qué hacer cuando se presiona el botón de retorno. Necesita saber de qué EditText estamos hablando (aquí uso exampleView), y luego necesita saber qué hacer cuando se presiona la tecla Enter (aquí, example_confirm () ). Si este es el último o único EditText en tu Actividad, debería hacer lo mismo que el método onClick para tu 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, establecer el oyente (lo más probable en su Método onCreate);

exampleView.setOnEditorActionListener(exampleListener);
 204
Author: Chad Hedgcock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-05 07:37:03
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;
    }
});
 201
Author: Jarod DY Law,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-22 07:46:14

Los teclados de hardware siempre producen eventos enter, pero los teclados de software devuelven diferentes actionIDs y nulls en EditTexts de una sola línea. Este código responde cada vez que el usuario presiona enter en un EditText en el que se ha establecido este receptor, independientemente del EditText o el 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 enter en singleLine=false da una flecha doblada en el teclado enter. Cuando singleLine = true en el último EditText la clave dice HECHO, y en los EditTexts anteriores dice SIGUIENTE. De forma predeterminada, este comportamiento es consistente en todos los emuladores de vanilla, Android y Google. El atributo scrollHorizontal no hace ninguna diferencia. La prueba null es importante porque la respuesta de los teléfonos a soft enters se deja al fabricante e incluso en los emuladores, los emuladores vanilla Level 16 responden a long soft enters en EditTexts multi-line y scrollHorizontal con un ActionID de NEXT y un null para el evento.

 32
Author: earlcasper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-07 19:18:37

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

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

Evita cualquier cosa que no sea texto y espacio. No pude tabular, "return" ("\n"), ni nada.

 19
Author: Newbie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-03 13:18:11

Al igual que un anexo a la respuesta de Chad (que funcionó casi perfectamente para mí), descubrí que necesitaba agregar una verificación en el tipo de acción KeyEvent para evitar que mi código se ejecute dos veces (una en el evento key-up y otra en el evento key-down).

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

Véase http://developer.android.com/reference/android/view/KeyEvent.html para obtener información sobre la repetición de eventos de acción (manteniendo pulsada la tecla enter), etc.

 15
Author: kermitology,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-23 15:29:45

Tenía un propósito similar. Quería resolver presionando la tecla "Enter" en el teclado (que quería personalizar) en un AutoCompleteTextView 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) de SwiftKey 3 (donde funcionaba perfectamente) al teclado estándar de Android (donde en lugar de manejar mi código desde el receptor, se introdujo una nueva línea después de pulsando la tecla "Enter". Me llevó un tiempo manejar este problema, pero no se si funcionará bajo todas las circunstancias sin importar qué tipo de entrada uses.

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

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

android:inputType="text"

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

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

Establezca un OnEditorActionListener en 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 vuelven loco.

 14
Author: kaolick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-20 14:57:37

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

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

Establezca el android:imeOptionsluego simplemente verifique el ActionID en onEditorAction. Así que si usted establece imeOptions a 'actionDone' entonces usted buscaría ' ActionID = = EditorInfo.IME_ACTION_DONE ' en onEditorAction. También, asegúrese de establecer el android: inputType.

Aquí está el EditText del ejemplo vinculado arriba:

<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 usando la función setImeOptions(int). Aquí está el OnEditorActionListener del ejemplo enlazado arriba:

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;
    }
});
 11
Author: Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-04 17:35:49

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 el 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 clave de entrada. La tecla Enter en el teclado cambiará de "Enter" a "Done". Así que cuando se presiona la tecla Enter, se activará esta acción y por lo tanto se manejará.

 10
Author: Akshayraj Kore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-23 15:07:43

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;
        }
    });
 7
Author: Xar E Ahmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-21 12:27:18
     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 mí
Además ocultar teclado

 5
Author: V. Kalyuzhnyu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 15:20:57

Primero, debe configurar EditText listen para presionar la tecla

@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 al presionar la tecla, por ejemplo, evento para establecer 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 finalmente, 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;
 3
Author: LifeiSHot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-08 03:26:31

Funciona 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");

        }
    });
}

}

Funciona perfectamente

 3
Author: Domi mtz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-01 21:45:53

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

edit.setInputType(InputType.TYPE_CLASS_TEXT);
 3
Author: Milan Švec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-15 04:48:21

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!");
                    }
           }
          });
 2
Author: ORY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-02 19:03:45

Una forma confiable de responder a un en un EditText es con un TextWatcher, un LocalBroadcastManager y un BroadcastReceiver. Necesita agregar la biblioteca de soporte v4 para usar LocalBroadcastManager. Utilizo el tutorial en vogella.com : 7.3 "Eventos de difusión local con LocalBroadcastManager" debido a su ejemplo de código conciso completo. En onTextChanged antes de es el índice del final del cambio antes de la cambio>;menos inicio. Cuando en el TextWatcher el subproceso de interfaz de usuario está ocupado actualizando EditText editable, por lo que enviamos una Intent para activar el BroadcastReceiver cuando el subproceso de interfaz de usuario se realiza 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
 1
Author: earlcasper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-21 22:17:27

InputType en el campo de texto debe ser "text" para que funcione lo que CommonsWare dijo. Acabo de probar todo esto, no inputType antes de la prueba y nada funcionó, Enter siguió registrándose como soft enter. Después de inputType = text, todo, incluido el setImeLabel, funcionó.

 1
Author: Odaym,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-07 14:56:35
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" />
 1
Author: kreker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-09 17:39:49

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

Acaba de añadir estos depencendy:

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
 1
Author: Jacky Supit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 10:29:37

Aquí hay una función estática simple que puede lanzar en su clase Utils o Keyboards que ejecutará el código cuando el usuario presione la tecla return 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;
        }
    };
}
 0
Author: JohnnyLambada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-12 18:31:04