Utilice la tecla" ENTER " en softkeyboard en lugar de hacer clic en el botón


Hola Tengo una búsqueda EditText y una búsqueda Button. Cuando escribo el texto buscado, me gustaría usar la tecla ENTER en el softkeyboard en lugar de buscar Button para activar la función de búsqueda.

Gracias por la ayuda de antemano.

Author: Peter O., 2010-12-15

6 answers

Lo haces estableciendo un OnKeyListener en tu EditText.

Aquí hay un ejemplo de mi propio código. Tengo un EditText llamado addCourseText, que llamará a la función addCourseFromTextBox cuando se haga clic en la tecla enter o en el d-pad.

addCourseText = (EditText) findViewById(R.id.clEtAddCourse);
addCourseText.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch (keyCode)
            {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    addCourseFromTextBox();
                    return true;
                default:
                    break;
            }
        }
        return false;
    }
});
 127
Author: Nailuj,
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
2010-12-15 15:43:54
<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" />

Luego puede escuchar si presiona el botón de acción definiendo un TextView.OnEditorActionListener para el elemento EditText. En el receptor, responda al ID de acción IME apropiado definido en la clase EditorInfo, como IME_ACTION_SEND. Por ejemplo:

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

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

 31
Author: tieorange,
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-07-05 20:14:59

Puede ser que pueda agregar un atributo a su EditText como este:

android:imeOptions="actionSearch"
 25
Author: itemon,
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
2010-12-15 16:07:24

Añadir un atributo al EditText como android: imeOptions = "actionSearch"

Esta es la mejor manera de hacer la función

Y las imeopciones también tienen algunos otros valores como " go " 、 "next" 、 "done", etc.

 5
Author: ruyi.zhu,
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-01-24 12:20:24

Para evitar que el foco avance al siguiente campo editable (si tiene uno), es posible que desee ignorar los eventos key-down, pero manejar los eventos key-up. También prefiero filtrar primero en el código clave, asumiendo que sería marginalmente más eficiente. Por cierto, recuerde que devolver true significa que usted ha manejado el evento, por lo que ningún otro oyente lo hará. De todos modos, aquí está mi versión.

ETFind.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (keyCode ==  KeyEvent.KEYCODE_DPAD_CENTER
        || keyCode ==  KeyEvent.KEYCODE_ENTER) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                // do nothing yet
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                        findForward();      
            } // is there any other option here?...

            // Regardless of what we did above,
            // we do not want to propagate the Enter key up
            // since it was our task to handle it.
            return true;

        } else {
            // it is not an Enter key - let others handle the event
            return false;
        }
    }

});
 0
Author: Wojtek Jarosz,
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-26 09:24:45

Esta es una muestra de una de mis aplicaciones cómo manejo

 //searching for the Edit Text in the view    
    final EditText myEditText =(EditText)view.findViewById(R.id.myEditText);
        myEditText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                 if (event.getAction() == KeyEvent.ACTION_DOWN)
                      if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                             (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                //do something
                                //true because you handle the event
                                return true;
                               }
                       return false;
                       }
        });
 0
Author: Manuel Alejandro Diaz Serret,
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-12 14:43:41