2011-11-22 15 views
12

He estado siguiendo los tutoriales oficiales de Android y de alguna manera estoy teniendo un problema con this very simple example para ejecutar una función después de presionar "Enter" para un EditText.Android ejecutar la función después de presionar "Enter" para EditText

entiendo lo que tengo que hacer y parecen tener todo configurado correctamente, pero se queja de Eclipse con esta línea:

edittext.setOnKeyListener(new OnKeyListener() { 

subraya setOnKeyListener con el error:

The method setOnKeyListener(View.OnKeyListener) in the type View is not applicable for the arguments (new DialogInterface.OnKeyListener(){})

Y también subraya OnKeyListener con el error:

The type new DialogInterface.OnKeyListener(){} must implement the inherited abstract method DialogInterface.OnKeyListener.onKey(DialogInterface, int, KeyEvent)

¿Quizás alguien pueda dispararme en la dirección correcta? Antes de probar otras soluciones (que ya he encontrado en stackoverflow), realmente me gustaría resolver esto porque me tiene nervioso que algo tan simple de seguir, como un tutorial oficial, no parece funcionar.

Gracias de antemano.

+0

Algo como esto? http://stackoverflow.com/questions/4451374/use-enter-key-on-softkeyboard-instead-of-clicking-button/4451825#4451825 – AedonEtLIRA

Respuesta

13

Por lo que puedo ver, parece que tiene una importación incorrecta.

Trate

edittext.setOnKeyListener(new View.OnKeyListener() { 

o añadir esta importación

import android.view.View.OnKeyListener; 

y retire éste

import android.content.DialogInterface.OnKeyListener; 
+0

Excelente, gracias por explicar por qué no funcionó. Tendré que ser muy cuidadoso con mis importaciones a partir de ahora :) – user1060582

+0

no funciona para mí – saravanan

2

Elimine la instrucción de importación que tiene DialogInterface, luego importe View.OnKeyListener.

+1

Hermoso, muchas gracias! Eso es lo que obtengo para aprender CTRL + SHFT + O antes que nada. Gracias a todos los que respondieron, este sitio es una ayuda fantástica. – user1060582

49

Para recibir un evento de teclado, una vista necesidad tienen foco. Para obligar a este uso:

edittext.setFocusableInTouchMode(true); 
edittext.requestFocus(); 

Después de que continúe con el mismo código en el ejemplo:

edittext.setOnKeyListener(new View.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; 
    } 
}); 
+0

fantástico, gracias !!! Finalmente estoy aprendiendo la programación de Android #boilerplate –

Cuestiones relacionadas