2010-03-12 18 views
27

Cuando mi usuario presiona Ingrese en la "entrada validada de usuario" de android virtual! keybord my keybord permanecer visible! (¿Por qué?)

android conjunto oculto el teclado al presionar enter (en un EditText)

Aquí mi código Java ...

private void initTextField() { 
    entryUser = (EditText) findViewById(R.id.studentEntrySalary); 
    entryUser.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: 
         userValidateEntry(); 
         return true; 
       } 
      } 

      return true; 
     } 
    }); 
} 

private void userValidateEntry() { 
    System.out.println("user validate entry!"); 
} 

... aquí mi punto de vista

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> 
      <EditText android:id="@+id/studentEntrySalary" android:text="Foo" android:layout_width="wrap_content" android:layout_height="wrap_content" /> 
</LinearLayout> 

Tal vez algo mal en mi dispositivo virtual?

eliminado enlace ImageShack muertos

Respuesta

66

Esto debe hacerlo:

yourEditTextHere.setOnEditorActionListener(new OnEditorActionListener() { 

     @Override 
     public boolean onEditorAction(TextView v, int actionId, 
       KeyEvent event) { 
      if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { 
       InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 

       // NOTE: In the author's example, he uses an identifier 
       // called searchBar. If setting this code on your EditText 
       // then use v.getWindowToken() as a reference to your 
       // EditText is passed into this callback as a TextView 

       in.hideSoftInputFromWindow(searchBar 
         .getApplicationWindowToken(), 
         InputMethodManager.HIDE_NOT_ALWAYS); 
       userValidateEntry(); 
       // Must return true here to consume event 
       return true; 

      } 
      return false; 
     } 
    }); 
+2

¡Tu un género! Gracias (Modificar búsquedaBar comprar suEditTextHere) –

+1

1. El código parece no funcionar cuando cambio el código a if (event! = Null && (event.getKeyCode() == KeyEvent.KEYCODE_D)) Así que después de presionar D el soft el formulario de entrada no se oculta. – Samir

+5

Para cualquier otra persona que vea el comentario de Samir, es porque este código establece el 'OnEditorActionListener', que solo se invoca cuando se pulsa una tecla como Enter, y no las teclas de caracteres normales. –

5

Si realiza el cuadro de texto de una sola línea (creo que la estructura está llamado SingleLine a los archivos del formato XML) saldrá fuera del teclado en entrar.

Aquí van: http://developer.android.com/reference/android/R.styleable.html#TextView_singleLine

+2

negativo. Todavía es el mismo problema con android: singleLine = "true" –

+0

Esto funciona para mí con Android 4 (Tablet 4.0.3, build target 4.2) en caso de que sea dependiente de la versión de Android (no lo he probado en otras versiones). – Mick

18

Mantenga el SingleLine = "true" y añadir imeOptions = "actionDone" al EditarTexto. Luego, en el OnEditorActionListener comprobar si ActionID == EditorInfo.IME_ACTION_DONE, al igual que (pero el cambio a su aplicación):

if (actionId == EditorInfo.IME_ACTION_DONE) { 

       if ((username.getText().toString().length() > 0) 
         && (password.getText().toString().length() > 0)) { 
        // Perform action on key press 
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(username.getWindowToken(), 
          0); 
        doLogin(); 
       } 
      } 
+6

En mi caso, 'imeOptions =" ​​actionDone "' era suficiente, no se necesitaba código. – 1615903

1

Soy crear un componente personalizado que se extiende AutoCompleteTextView, como en el siguiente ejemplo:

public class PortugueseCompleteTextView extends AutoCompleteTextView { 
... 
@Override 
public boolean onKeyPreIme(int keyCode, KeyEvent event) { 
    if (event != null && (event.getKeyCode() == KeyEvent.KEYCODE_BACK)) { 
     InputMethodManager inputManager = 
       (InputMethodManager) getContext(). 
         getSystemService(Context.INPUT_METHOD_SERVICE); 
     inputManager.hideSoftInputFromWindow(
       this.getWindowToken(), 
       InputMethodManager.HIDE_NOT_ALWAYS); 
    } 
    return super.onKeyPreIme(keyCode, event); 
} 

Estoy utilizando este código en AlertDialog.Builder, pero es posible utilizarlo en Activity.

Cuestiones relacionadas