type textcapsentences studio propiedades inputtype imeactionid example edittext android android-edittext ime

textcapsentences - propiedades de edittext android



¿Cómo manejo el botón hecho de ImeOptions? (6)

Más detalles sobre cómo configurar el OnKeyListener y hacer que escuche el botón Hecho.

Primero agregue OnKeyListener a la sección de implementaciones de su clase. A continuación, agregue la función definida en la interfaz OnKeyListener:

/* * Respond to soft keyboard events, look for the DONE press on the password field. */ public boolean onKey(View v, int keyCode, KeyEvent event) { if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Done pressed! Do something here. } // Returning false allows other listeners to react to the press. return false; }

Dado un objeto EditText:

EditText textField = (EditText)findViewById(R.id.MyEditText); textField.setOnKeyListener(this);

Tengo un EditText donde estoy configurando la siguiente propiedad para que pueda mostrar el botón hecho en el teclado cuando el usuario hace clic en EditText.

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

Cuando el usuario hace clic en el botón hecho en el teclado de la pantalla (terminado de escribir), quiero cambiar el estado de RadioButton .

¿Cómo puedo rastrear el botón hecho cuando se golpea desde el teclado de la pantalla?


Pruebe esto, debería funcionar para lo que necesita:

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(EditText v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { //do here your stuff f return true; } return false; } });


Sé que esta pregunta es antigua, pero quiero señalar lo que funcionó para mí.

Intenté usar el código de muestra del sitio web de Desarrolladores de Android (que se muestra a continuación), pero no funcionó. Así que revisé la clase EditorInfo y me di cuenta de que el valor entero IME_ACTION_SEND se especificaba como 0x00000004 .

Código de ejemplo de los desarrolladores de Android:

editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextEmail .setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { /* handle action here */ handled = true; } return handled; } });

Entonces, agregué el valor entero a mi archivo res/values/integers.xml .

<?xml version="1.0" encoding="utf-8"?> <resources> <integer name="send">0x00000004</integer> </resources>

Luego, edité mi archivo de diseño res/layouts/activity_home.xml siguiente manera

<EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeActionId="@integer/send" android:imeActionLabel="@+string/send_label" android:imeOptions="actionSend" android:inputType="textEmailAddress"/>

Y luego, el código de muestra funcionó.


Si bien la mayoría de las personas respondieron la pregunta directamente, quería dar más información sobre el concepto detrás de ella. En primer lugar, me llamó la atención de IME cuando creé una Actividad de inicio de sesión predeterminada. Se generó un código para mí que incluye lo siguiente:

<EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_password" android:imeActionId="@+id/login" android:imeActionLabel="@string/action_sign_in_short" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:singleLine="true"/>

Ya debería estar familiarizado con el atributo inputType. Esto solo informa a Android el tipo de texto esperado, como una dirección de correo electrónico, contraseña o número de teléfono. La lista completa de valores posibles se puede encontrar here .

Fue, sin embargo, el atributo imeOptions="actionUnspecified" que no entendí su propósito. Android le permite interactuar con el teclado que aparece desde la parte inferior de la pantalla cuando se selecciona texto usando InputMethodManager . En la esquina inferior del teclado, hay un botón, generalmente dice "Siguiente" o "Hecho", dependiendo del campo de texto actual. Android te permite personalizar esto usando android:imeOptions . Puede especificar un botón "Enviar" o un botón "Siguiente". La lista completa se puede encontrar here .

Con eso, puede escuchar las pulsaciones del botón de acción definiendo un TextView.OnEditorActionListener para el elemento EditText . Como en tu ejemplo:

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(EditText v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { //do here your stuff f return true; } return false; } });

Ahora, en mi ejemplo, tenía el android:imeOptions="actionUnspecified" . Esto es útil cuando desea intentar iniciar sesión en un usuario cuando presiona la tecla Intro. En su actividad, puede detectar esta etiqueta y luego intentar el inicio de sesión:

mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } });


Terminé con una combinación de respuestas de Roberts y chirags:

((EditText)findViewById(R.id.search_field)).setOnEditorActionListener( new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // Identifier of the action. This will be either the identifier you supplied, // or EditorInfo.IME_NULL if being called due to the enter key being pressed. if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { onSearchAction(v); return true; } // Return true if you have consumed the action, else false. return false; } });

Actualización: El código anterior algunas veces activaría la devolución de llamada dos veces. En cambio, opté por el siguiente código, que obtuve de los clientes de chat de Google:

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // If triggered by an enter key, this is the event; otherwise, this is null. if (event != null) { // if shift key is down, then we want to insert the ''/n'' char in the TextView; // otherwise, the default action is to send the message. if (!event.isShiftPressed()) { if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } return true; } return false; } if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } return true; }


<EditText android:imeOptions="actionDone" android:inputType="text"/>

entonces, el código de Java es,

edittext.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((actionId == EditorInfo.IME_ACTION_DONE)) { Log.i(TAG,"Here you can write the code"); } return false; } });