Teclado emergente automático al iniciar la actividad


Tengo una pregunta relativamente simple. Tengo una actividad con un montón de EditText en ellos. Cuando abro la actividad se enfoca automáticamente al primer EditText y muestra el teclado virtual.

¿Cómo puedo evitar esto?

Author: Vikas Patidar, 2011-01-12

16 answers

Utilice estos atributos en su etiqueta de diseño en el archivo XML:

android:focusable="true"
android:focusableInTouchMode="true"

Como informaron otros miembros en los comentarios, no funciona en ScrollView, por lo tanto, debe agregar estos atributos al hijo principal de ScrollView.

 199
Author: Vikas Patidar,
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
2016-06-02 11:19:41

Puedes agregar esto a tu actividad de Manifiesto de Android:

android:windowSoftInputMode="stateHidden|adjustResize"
 94
Author: Mobile Bloke,
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
2012-09-05 11:54:08

Tengo varias implementaciones descritas aquí, pero ahora he agregado en el AndroidManifest.xml para mi Activity la propiedad:

android:windowSoftInputMode="stateAlwaysHidden"

Creo que esta es la manera fácil, incluso si está utilizando fragments.

"stateAlwaysHidden" El teclado de software siempre está oculto cuando el la ventana principal de la actividad tiene el foco de entrada.

 30
Author: Jorgesys,
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-01-16 17:54:08

Si tienes otra vista de tu actividad como ListView, también puedes hacer:

ListView.requestFocus(); 

En tu onResume() para tomar el foco de editText.

Sé que esta pregunta ha sido respondida, pero solo proporciona una solución alternativa que funcionó para mí:)

 11
Author: Sid,
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
2014-04-30 16:46:09

Https://stackoverflow.com/a/11627976/5217837 Esto es casi correcto:

@Override
public void onCreate(Bundle savedInstanceState) {

getWindow().setSoftInputMode(
   WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

}

Pero debería ser SOFT_INPUT_STATE_HIDDEN en lugar de SOFT_INPUT_STATE_ALWAYS_VISIBLE

 4
Author: Brent Young,
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-05-23 11:47:28

Usa esto en el código de tu Actividad:

@Override
public void onCreate(Bundle savedInstanceState) {

getWindow().setSoftInputMode(
   WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

}
 3
Author: Bobs,
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
2012-07-24 09:31:30

Tuve un problema simular, incluso cuando el cambio de pestañas el teclado apareció automáticamente y se quedó arriba, con Android 3.2.1 en una tableta. Utilice el siguiente método:

public void setEditTextFocus(EditText searchEditText, boolean isFocused)
{
    searchEditText.setCursorVisible(isFocused);
    searchEditText.setFocusable(isFocused);
    searchEditText.setFocusableInTouchMode(isFocused);
    if (isFocused) {
        searchEditText.requestFocus();
    } else {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputManager.hideSoftInputFromWindow(searchEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS );
    }
}   

En el onCreate() y en el onPause () de la actividad para cada EditText:

setEditTextFocus (Myeditext, false);

Para cada EditText un OnTouchListener:

    myEditText.setOnTouchListener(new EditText.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            setEditTextFocus(myEditText, true); 
            return false;
        }
    });

Para cada EditText en el OnEditorActionListener:

    myEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                            .......
            setEditTextFocus(myEditText, false); 
            return false;
        }
    });

Y para cada EditText en el layout xml:

            android:imeOptions="actionDone"
            android:inputType="numberDecimal|numberSigned" // Or something else

Hay probablemente más código optimizando posible.

 3
Author: Zekitez,
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
2012-10-29 01:20:19

He encontrado esta solución simple que funcionó para mí.Establezca estos atributos en su diseño padre:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLayout"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true" >

Y ahora, cuando se inicia la actividad, este diseño principal se enfocará por defecto.

También, podemos eliminar el foco de las vistas secundarias en tiempo de ejecución dando el foco al diseño principal de nuevo, así:

findViewById(R.id.mainLayout).requestFocus();

Espero que funcione para ti .

 2
Author: Salman Nazir,
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
2016-05-19 06:32:41
((InputMethodManager)getActivity().getSystemService("input_method")).hideSoftInputFromWindow(this.edittxt.getWindowToken(), 0);
 2
Author: Sreelal S,
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
2016-11-14 11:56:44

Esta es la solución que estoy usando, no es la mejor solución, pero está funcionando bien para mí

 editComment.setFocusableInTouchMode(false);
 editComment.setOnTouchListener(new OnTouchListener(){

                @Override
                public boolean onTouch(View v, MotionEvent event)
                {
                    // TODO Auto-generated method stub
                    editComment.setFocusableInTouchMode(true);
                     editComment.requestFocus() ;
                    return false;
                }});
 1
Author: Paul Roosens,
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-01-22 11:13:06

Curiosamente, esta documentación https://developer.android.com/training/keyboard-input/visibility.html indica que cuando se inicia una actividad y se enfoca un campo de texto, el teclado de software no se muestra (y luego continúa para mostrarle cómo se muestra el teclado si desea con algún código).

En mi Samsung Galaxy S5, así es como funciona mi aplicación (sin entrada de manifiesto o código específico) no sin teclado de software. Sin embargo, en un Lollipop AVD, se muestra un teclado de software -- contraviniendo el documento dado anteriormente.

Si obtiene este comportamiento al realizar pruebas en un AVD, es posible que desee realizar pruebas en un dispositivo real para ver qué sucede.

 1
Author: Steve Waring,
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-05-12 13:50:18

Esto tiene algunas buenas respuestas en el siguiente post : Detener EditText de ganar el foco en el inicio de la actividad. El que uso regularmente es el siguiente código de Morgan :

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:focusable="true" 
    android:focusableInTouchMode="true"
    android:layout_width="0px" 
    android:layout_height="0px"/>

<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:nextFocusUp="@id/autotext"     
    android:nextFocusLeft="@id/autotext"/>

NOTA: El elemento ficticio debe COLOCARSE JUSTO ANTES del elemento enfocable.

Y creo que debería funcionar perfectamente incluso con ScrollView y tampoco he tenido ningún problema con la accesibilidad para esto.

 1
Author: Kaushik NP,
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-05-23 12:18:20

Esto ocurre cuando su EditText se enfoca automáticamente como cuando comienza su actividad. Así que una forma fácil y estable de solucionar esto, es simplemente establecer el enfoque inicial a cualquier otra vista, como un botón, etc.

Puede hacer esto en su XML de diseño, sin necesidad de código..

 0
Author: Mtl Dev,
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
2016-03-18 00:53:41

Respuesta aceptada no está funcionando para mí, es por eso que dar respuesta solución de trabajo, puede ser que es útil !

EditText edt = (EditText) findViewById(R.id.edt);
edt.requestFocus();    
edt.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
edt.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));

Ahora el teclado está abierto enjoy :)

 0
Author: Yogesh Rathi,
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
2016-10-07 07:27:27

Android: windowSoftInputMode= "stateHidden / adjustResize"

Funciona bien

 0
Author: Softlabsindia,
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
2018-03-20 11:36:30

Si su vista tiene EditText y Listview, el teclado se abrirá de forma predeterminada. Para ocultar el teclado de aparecer por defecto hacer lo siguiente

this.listView.requestFocus();

Asegúrese de que está solicitando el enfoque en listview después de obtener view para EditText.

Por ejemplo,

this.listView = (ListView) this.findViewById(R.id.list);
this.editTextSearch = (EditText) this.findViewById(R.id.editTextSearch);
this.listView.requestFocus();

Si lo hace, EditText obtendrá el enfoque y el teclado aparecerá.

 -1
Author: Pritesh Shah,
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
2012-05-30 20:02:47