Evitar que EditText se centre en el inicio de la actividad


Tengo un Activity en Android, con dos elementos:

  1. EditText
  2. ListView

Cuando se inicia mi Activity, el EditText inmediatamente tiene el foco de entrada (cursor intermitente). No quiero que ningún control tenga un enfoque de entrada al inicio. Lo intenté:

EditText.setSelected(false);

No hubo suerte. ¿Cómo puedo convencer al EditText de no seleccionarse a sí mismo cuando comienza el Activity?

Author: Pankaj Lilan, 2009-10-12

30 answers

Excelentes respuestas de Luc y Mark sin embargo falta un buen ejemplo de código. Agregar la etiqueta android:focusableInTouchMode="true" a <LinearLayout> como en el siguiente ejemplo solucionará el problema.

<!-- 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"/>
 2107
Author: Morgan Christiansson,
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-07-27 21:33:34

¿Es el problema real que simplemente no quieres que tenga enfoque en absoluto? ¿O no quieres que muestre el teclado virtual como resultado de enfocar el EditText? Realmente no veo un problema con el EditText tener foco en el inicio, pero definitivamente es un problema tener la ventana softInput abierta cuando el usuario no solicitó explícitamente centrarse en el EditText (y abrir el teclado como resultado).

Si es el problema del teclado virtual, consulte la AndroidManifest.xml elemento documentación.

android:windowSoftInputMode="stateHidden" - siempre escóndelo al entrar en la actividad.

O android:windowSoftInputMode="stateUnchanged" - no cambiarlo (por ejemplo, no mostrar si no está ya mostrado, pero si estaba abierto al entrar en la actividad, déjelo abierto).

 1585
Author: Joe,
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-08-11 17:02:33

Existe una solución más simple. 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 (por ejemplo, después de terminar la edición secundaria) dando el foco al diseño principal de nuevo, de esta manera:

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

Buen comentario de Guillaume Perrot:

android:descendantFocusability="beforeDescendants" parece ser el por defecto (el valor entero es 0). Funciona simplemente añadiendo android:focusableInTouchMode="true".

Realmente, podemos ver que el beforeDescendants establecido como predeterminado en el método ViewGroup.initViewGroup() (Android 2.2.2). Pero no igual a 0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

Gracias a Guillaume.

 1037
Author: Silver,
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-08-14 19:13:16

La única solución que he encontrado es:

  • Crea un LinearLayout (No sé si funcionarán otros tipos de Maquetación)
  • Establece los atributos android:focusable="true" y android:focusableInTouchMode="true"

Y el EditText no obtendrá el enfoque después de iniciar la actividad

 394
Author: Luc,
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-10-21 22:30:47

El problema parece provenir de una propiedad que solo puedo ver en el XML form del layout.

Asegúrese de eliminar esta línea al final de la declaración dentro de las etiquetas XML EditText:

<requestFocus />

Eso debería dar algo así:

<EditText
   android:id="@+id/emailField"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textEmailAddress">

   //<requestFocus /> /* <-- without this line */
</EditText>
 71
Author: floydaddict,
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-10-21 21:17:10

Utilizando la información proporcionada por otros carteles, utilicé la siguiente solución:

En el XML de diseño

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

<!-- AUTOCOMPLETE -->
<AutoCompleteTextView
    android:id="@+id/autocomplete"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
    android:inputType="textNoSuggestions|textVisiblePassword"/>

En onCreate()

private AutoCompleteTextView mAutoCompleteTextView;
private LinearLayout mLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    //get references to UI components
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_focus);
}

Y finalmente, en onResume()

@Override
protected void onResume() {
    super.onResume();

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}
 64
Author: Someone Somewhere,
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-04-24 22:21:35

Lo siguiente detendrá edittext de tomar el foco cuando se crea, pero agarrarlo cuando los toque.

<EditText
    android:id="@+id/et_bonus_custom"
    android:focusable="false" />

Por lo que se establece focusable a false en el xml, pero la clave está en el java, que se agrega el siguiente receptor:

etBonus.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        return false;
    }
});

Debido a que estás devolviendo false, es decir, no consumiendo el evento, el comportamiento de focusing procederá como de costumbre.

 60
Author: MinceMan,
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-04-24 21:43:56

Try clearFocus() en lugar de setSelected(false). Cada vista en Android tiene tanto capacidad de enfoque como de selección, y creo que solo quieres despejar el enfoque.

 59
Author: Konklone,
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-10-22 05:09:00

Había intentado varias respuestas individualmente, pero el enfoque sigue siendo el EditText. Solo me las arreglé para resolverlo mediante el uso de dos de la solución a continuación juntos.

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

(Referencia de Silver https://stackoverflow.com/a/8639921/15695 )

Y eliminar

 <requestFocus />

En EditText

( Referencia de floydaddict https://stackoverflow.com/a/9681809 )

 45
Author: Lee Yi Hong,
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-10-10 05:49:44

Ninguna de estas soluciones funcionó para mí. La forma en que arreglé el enfoque automático fue:

<activity android:name=".android.InviteFriendsActivity" android:windowSoftInputMode="adjustPan">
    <intent-filter >
    </intent-filter>
</activity>
 38
Author: rallat,
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
2011-11-30 16:37:52

Solución simple: In AndroidManifest in Activity tag use

android:windowSoftInputMode="stateAlwaysHidden"
 33
Author: Sergey Sheleg,
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-09-27 10:05:40

Simplemente puede configurar "enfocable" y "enfocable en modo táctil" para el valor verdadero en el primer TextView de layout. De esta manera cuando la actividad se inicia el TextView estará enfocado pero , debido a su naturaleza, no verá nada enfocado en la pantalla y ,por supuesto, no habrá ningún teclado mostrado...

 30
Author: Zeus,
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-09-27 18:13:21

Lo siguiente funcionó para mí en Manifest. Escribe,

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
 29
Author: Babar Sanah,
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-09-27 10:05:28

Necesitaba aclarar el enfoque de todos los campos programáticamente. Acabo de agregar las siguientes dos declaraciones a mi definición de diseño principal.

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);

Eso es todo. Solucionado mi problema al instante. Gracias, Silver, por señalarme en la dirección correcta.

 25
Author: jakeneff,
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-27 23:35:28

Agregue android:windowSoftInputMode="stateAlwaysHidden" en la etiqueta de actividad del archivo Manifest.xml.

Fuente

 24
Author: prgmrDev,
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-09-27 10:04:40

La respuesta más simple, simplemente agregue esto en el diseño principal del XML.

android:focusable="true" 
android:focusableInTouchMode="true"
 24
Author: Rishabh Saxena,
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-04-18 06:14:56

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

ListView.requestFocus(); 

En su onResume() para captar el foco de la editText.

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

 19
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
2013-09-27 18:11:18

Pruebe esto antes de su primer campo editable:

<TextView  
        android:id="@+id/dummyfocus" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="@string/foo"
        />

----

findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
findViewById(R.id.dummyfocus).requestFocus();
 18
Author: Jack Slater,
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
2011-06-12 00:41:21

Añádase lo siguiente en el método onCreate:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 18
Author: Vishal Raj,
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-09-27 10:04:26

Siendo que no me gusta contaminar el XML con algo que está relacionado con la funcionalidad, he creado este método que "transparentemente" roba el foco de la primera vista enfocable y luego se asegura de eliminarse cuando sea necesario!

public static View preventInitialFocus(final Activity activity)
{
    final ViewGroup content = (ViewGroup)activity.findViewById(android.R.id.content);
    final View root = content.getChildAt(0);
    if (root == null) return null;
    final View focusDummy = new View(activity);
    final View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean b)
        {
            view.setOnFocusChangeListener(null);
            content.removeView(focusDummy);
        }
    };
    focusDummy.setFocusable(true);
    focusDummy.setFocusableInTouchMode(true);
    content.addView(focusDummy, 0, new LinearLayout.LayoutParams(0, 0));
    if (root instanceof ViewGroup)
    {
        final ViewGroup _root = (ViewGroup)root;
        for (int i = 1, children = _root.getChildCount(); i < children; i++)
        {
            final View child = _root.getChildAt(i);
            if (child.isFocusable() || child.isFocusableInTouchMode())
            {
                child.setOnFocusChangeListener(onFocusChangeListener);
                break;
            }
        }
    }
    else if (root.isFocusable() || root.isFocusableInTouchMode())
        root.setOnFocusChangeListener(onFocusChangeListener);

    return focusDummy;
}
 13
Author: Takhion,
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-04-24 13:26:14

Tarde, pero quizás útil. Cree un texto ficticio en la parte superior de su diseño y luego llame a myDummyEditText.requestFocus() en onCreate()

<EditText android:id="@+id/dummyEditTextFocus" 
android:layout_width="0px"
android:layout_height="0px" />

Eso parece comportarse como espero. No es necesario manejar cambios de configuración, etc. Necesitaba esto para una actividad con un largo TextView (instrucciones).

 12
Author: Jim,
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
2011-02-13 01:58:17

Sí, hice lo mismo: crear un diseño lineal 'ficticio' que obtenga el enfoque inicial. Además, configuré los ID de enfoque' siguiente ' para que el usuario no pueda enfocarlo más después de desplazarse una vez:

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());

dummy.setNextFocusUpId(et.getId());

et.setNextFocusUpId(et.getId());

Mucho trabajo solo para deshacerse del enfoque en una vista..

Gracias

 12
Author: mark,
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-09-27 18:13:04

Escribe esta línea en tu Diseño Padre...

 android:focusableInTouchMode="true"
 11
Author: Vishal Vaishnav,
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-07-26 09:52:46

Para mí, lo que funcionó en todos los dispositivos es esto:

    <!-- fake first focusable view, to allow stealing the focus to itself when clearing the focus from others -->

    <View
    android:layout_width="0px"
    android:layout_height="0px"
    android:focusable="true"
    android:focusableInTouchMode="true" />

Simplemente ponga esto como una vista antes de la vista enfocada problemática, y eso es todo.

 10
Author: android developer,
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-05-14 08:02:14

Esta es la solución perfecta y más fácil.Siempre uso esto en mi aplicación.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
 9
Author: ,
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-03-31 09:27:09

Lo más sencillo que hice fue poner el foco en otra vista en onCreate:

    myView.setFocusableInTouchMode(true);
    myView.requestFocus();

Esto detuvo el teclado de software que aparece y no había ningún cursor parpadeando en el EditText.

 8
Author: Lumis,
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-03 06:57:31

Escriba este código dentro del archivo Manifest en el Activity donde no desea abrir el teclado.

android:windowSoftInputMode="stateHidden"

Archivo de manifiesto:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.projectt"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="24" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
         <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            **android:windowSoftInputMode="stateHidden"**
            android:label="@string/app_name" >
        </activity>

    </application>

</manifest>
 7
Author: Tarit Ray,
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-03-15 07:21:33
<TextView
    android:id="@+id/TextView01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    style="@android:style/Widget.EditText"/>
 7
Author: atul,
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-03-31 18:41:46

En onCreate de su actividad, simplemente agregue use clearFocus() en su elemento EditText. Por ejemplo,

edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();

Y si quieres desviar el foco a otro elemento, usa requestFocus() en eso. Por ejemplo,

button = (Button) findViewById(R.id.button);
button.requestFocus();
 6
Author: Compaq LE2202x,
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-05-23 10:42:18

Puede lograr esto creando un maniquí EditText con ancho y alto de diseño establecido en 0dp, y solicitar el foco a esa vista. Agregue el siguiente fragmento de código en su diseño xml:

<EditText
    android:id="@+id/editText0"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/dummy"
    android:ems="10" 
    >
     <requestFocus />
    </EditText>
 6
Author: Ish,
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-09-27 10:04:54