2010-12-15 18 views

Respuesta

116

Lo haces configurando 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 hace clic en la tecla enter o 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; 
    } 
}); 
+0

Muchas gracias, funciona muy bien –

+4

En realidad, no se garantiza el suave llaves. Por ejemplo, no funciona para "ENTER" en Nexus 7 (Android 4.2) y para "BACK" lo hace. – Ghedeon

+0

MEJOR ejemplo que he visto! –

24

puede ser que podría añadir un atributo a su EditarTexto así:

android:imeOptions="actionSearch" 
+1

Esta es una solución más simple si está creando un texto de edición de búsqueda. – stevyhacker

5

añadir un atributo a la EditarTexto como android: imeOptions = "actionSearch"

este es el mejor forma de hacer la función

y las imeOptions también tienen algunos otros valores como "ir", "siguiente", "hecho", etc.

0

Para evitar que el enfoque avance al siguiente campo editable (si tiene uno) es posible que desee ignorar los eventos de desactivación, pero manejar eventos de activación. También prefiero filtrar primero en keyCode, suponiendo que sería marginalmente más eficiente. Por cierto, recuerda que regresar verdadero significa que has 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; 
     } 
    } 

}); 
27
<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" /> 

A continuación, puede escuchar presiona sobre el botón de acción mediante la definición de un TextView.OnEditorActionListener para el elemento EditarTexto. En su oyente, responda al ID de acción de 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

1

esto es una muestra de una de mi aplicación como 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; 
         } 
     }); 
Cuestiones relacionadas