Android: Fuerza EditText para eliminar el enfoque? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Me gustaría poder eliminar el foco del EditText. Por ejemplo, si aparece el Teclado y el usuario lo oculta con el botón atrás, me gustaría que el foco y el cursor desaparecieran. ¿Cómo se puede hacer?

Author: Alex1987, 2011-02-20

19 answers

Puede agregar esto a onCreate y ocultará el teclado cada vez que se inicie la actividad.

También puede cambiar programáticamente el foco a otro elemento.

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 214
Author: Wayner,
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-07-18 14:09:03

Puedes hacer desaparecer el cursor y el foco mediante

edittext.clearFocus();

Pero detectar cuando el teclado ocultar es un trabajo duro.

 273
Author: xtr,
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-05-25 05:59:01

Añade LinearLayout antes de EditText en tu XML.

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

O puede hacer lo mismo agregando estas líneas para ver antes de su 'EditText'.

<Button
    android:id="@+id/btnSearch"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center"
    android:text="Quick Search"
    android:textColor="#fff"
    android:textSize="13sp"
    android:textStyle="bold" />

<EditText
    android:id="@+id/edtSearch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:gravity="left"
    android:hint="Name"
    android:maxLines="1"
    android:singleLine="true"
    android:textColorHint="@color/blue"
    android:textSize="13sp"
    android:textStyle="bold" />
 120
Author: Singh Arjun,
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-06-15 09:23:22

Quita el foco pero permanece enfocado:

editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);

EditText perderá el enfoque, pero puede volver a obtenerlo en un nuevo evento táctil.

 76
Author: Paschalis,
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-01-13 19:18:45

Eliminar el enfoque automático edittext android

Está funcionando para mí

Editar En el enlace que sugieren usar LinearLayout, pero simple View funcionará

<View
    android:id="@+id/focus_thief"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:focusable="true"
    android:focusableInTouchMode="true" />

Entonces, si este "ladrón" se coloca en la parte superior del diseño (para ser el primer elemento enfocable), las llamadas a clearFocus() funcionarán.

 59
Author: sondt87,
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-10-14 12:53:02

Agregue estas dos propiedades a su diseño padre (por ejemplo: Diseño lineal, Diseño relativo)

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

Hará el truco:)

 43
Author: King of Masses,
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-14 05:39:00

También puedes incluir android:windowSoftInputMode="stateAlwaysHidden" en tu sección de acción de manifiesto.

Esto es equivalente a :

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Pero en forma XML.

Para su información, también puede ocultar el teclado con códigos:

// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);
 29
Author: Jarod DY Law,
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-08-26 22:55:15

Tienes que eliminar <requestFocus/>

Si no lo usa y sigue siendo el mismo problema

Usuario LinearLayout como padre y conjunto

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

Espero que te ayude.

 15
Author: Mohamed Hussien,
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-02-14 12:51:44

Intente usar esta en su vista funcionó para mí:

<View
    android:id="@+id/fucused"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"/>
 15
Author: ediBersh,
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-01-20 23:29:45

Agregue a su diseño padre dónde puso su EditText este android:focusableInTouchMode="true"

 11
Author: Context,
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-10-29 08:58:39

Para ocultar el teclado cuando se inicia la actividad.. escribe el siguiente código en onCreate ()..

InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

Para borrar el foco y eliminar el cursor de edittext.....

editText.clearFocus();

editText.setCursorVisible(false);
 11
Author: Pratibha Sarode,
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-11-17 12:12:54

Esta es mi primera respuesta sobre SO, así que no seas demasiado duro conmigo si hay errores. : D

Hay pocas respuestas flotando alrededor del SO, pero siento la necesidad de publicar mi solución completa porque esto me volvió loco. He cogido trozos y piezas de todo, así que perdóname si no doy créditos respectivos a todos... :)

(Simplificaré mi resultado porque mi vista tiene demasiados elementos y no quiero spam con eso e intentaré hacerlo tan genérico como posible...)

Para su diseño necesita un padre su EditText y vista padre definido algo como esto:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
              android:orientation="vertical"
              android:layout_width="match_parent" 
              android:layout_height="match_parent"
              android:id="@+id/lytContainer"
              android:descendantFocusability="beforeDescendants"
              android:focusableInTouchMode="true">
<EditText android:layout_width="fill_parent" 
              android:layout_height="wrap_content" 
              android:id="@+id/etEditor"
              android:inputType="number"
              android:layout_gravity="center" 
              android:hint="@string/enter_your_text"
              android:textColor="@android:color/darker_gray" 
              android:textSize="12dp"
              android:textAlignment="center" 
              android:gravity="center" 
              android:clickable="true"/>
</LinearLayout>

Así que, necesitaba algunas cosas aquí. Necesitaba tener un marcador de posición para mi EditText - que es eso -

Android:hint="hint"

También,

android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

Hizo que EditText no se centrara en ingresar la Actividad y más tarde en la Actividad en sí al configurar esta configuración ayuda para que pueda establecer OnTouchListeneren él para robar el foco de EditText.

Ahora, en la Actividad:

package com.at.keyboardhide;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

public class MainActivity extends Activity implements OnTouchListener{
private EditText getEditText;
private LinearLayout getLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    setContentView(R.layout.keyboardmain);
    getEditText = (EditText)findViewById(R.id.etEditor);
    getLinearLayout = (LinearLayout)findViewById(R.id.lytContainer);
    getLinearLayout.setOnTouchListener(this);

    getEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Log.d("EDTA", "text was entered.");
                getEditText.clearFocus();
                imm.hideSoftInputFromWindow(barcodeNo.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });
}
@Override
public boolean onTouch(View v, MotionEvent event) {
    if(v==getLinearLayout){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getEditText.getWindowToken(), 0);
        getEditText.clearFocus();
        return true;
        }
    return false;
    }
}

Algunas de las respuestas para bits que encontré en esta página de preguntas, y la parte con la solución de Actividad que encontré en este blog . El resto que me perdí y que tuve que averiguar yo mismo fue despejar el foco en el EditText que agregué a ambos dentro del setOnEditorActionListener y onTouchLister para la vista padre .

Espero que esto ayude a alguien y ahorre su tiempo. :)

Saludos, Z.

 9
Author: zed,
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-03-18 13:11:27

En los comentarios preguntó si se puede enfocar otra vista en lugar de EditText. Sí puede. Use el método .requestFocus() para la vista que desea enfocar al principio (en el método onCreate ())

También enfocar otra vista recortará cierta cantidad de código. (código para ocultar el teclado por ejemplo)

 6
Author: Nikola Despotoski,
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-07-26 15:49:47

También puedes incluir android:windowSoftInputMode="stateAlwaysHidden" en tu sección de acción de manifiesto.

Esto es equivalente a:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 3
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-04 06:20:11

Yo tenía el mismo problema. Me volvió más que loca.

Tenía un diálogo extendido con un ScrollView que tenía un TableLayout con LinearLayout extendido que contenía una SeekBar y un EditText.

El primer EditText siempre tenía enfoque automático después de mostrar el Diálogo y después de terminar de editar el texto sobre el teclado, el EditText todavía tenía el enfoque y el teclado todavía era visible.

Probé casi todas las soluciones de este hilo y ninguna funcionó para mí.

So aquí mi solución simple : (text = EditText)

text.setOnEditorActionListener( new OnEditorActionListener( ){
    public boolean onEditorAction( TextView v, int actionId, KeyEvent event ){
        if( (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) ||
            (actionId == EditorInfo.IME_ACTION_DONE) ){
            text.clearFocus( );
            InputMethodManager iMgr = null;
            iMgr = (InputMethodManager)mContext.getSystemService( Context.INPUT_METHOD_SERVICE );
            iMgr.hideSoftInputFromWindow( text.getWindowToken(), 0 );
        }
        return true;
    }
});

Por cierto, yo no usé ninguno de los siguientes fragmentos para resolverlo:

//setFocusableInTouchMode( true )
//setFocusable( true )
//setDescendantFocusability( ViewGroup.FOCUS_BEFORE_DESCENDANTS )

Y yo no usé un elemento espaciador como una Vista con ancho y alto de 1dp.

Esperemos que ayude a alguien: D

 3
Author: Pixtar,
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-08-21 11:49:21
editText.setFocusableInTouchMode(true)

El EditText podrá obtener el enfoque cuando el usuario lo toque. Cuando el diseño principal(actividad, diálogo, etc.) se hace visible el EditText no obtiene automáticamente el foco a pesar de que es la primera vista en el diseño.

 2
Author: Fabio Mitrano,
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-10-20 15:20:11
EditText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(URLText.getWindowToken(), 0); 
                    EditText.setFocusable(false);
                    EditText.setFocusableInTouchMode(true);
                    return true;
                } else {
                    return false;
                }
            }
        });
 2
Author: Abhi,
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-07-21 14:56:00

Puede evitar cualquier enfoque en sus elementos estableciendo el atributo android:descendantFocusability del elemento padre.

Aquí hay un ejemplo:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search__scroller"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ScrollView>

Aquí, el atributo android:descendantFocusability establecido en "blocksDescendants" bloquea el foco en los elementos secundarios.

Puedes encontrar más información aquí.

 0
Author: podpo,
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-07-13 02:59:37
check your xml file
 <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp" >

            **<requestFocus />**
 </EditText>


//Remove  **<requestFocus />** from xml
 -4
Author: SuSh,
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-02-07 12:23:32