Cómo ocultar Soft Keyboard cuando comienza la actividad


151

Tengo un Edittext con android:windowSoftInputMode="stateVisible"Manifest. Ahora se mostrará el teclado cuando empiece la actividad. ¿Cómo esconderlo? No puedo usar android:windowSoftInputMode="stateHiddenporque cuando el teclado está visible, minimice la aplicación y reanude el teclado debe estar visible. Lo intenté con

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

Pero no funcionó.

Respuestas:


1

Si no quieres usar xml, crea una extensión de Kotlin para ocultar el teclado

// In onResume, call this
myView.hideKeyboard()

fun View.hideKeyboard() {
    val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

Alternativas basadas en casos de uso:

fun Fragment.hideKeyboard() {
    view?.let { activity?.hideKeyboard(it) }
}

fun Activity.hideKeyboard() {
    // Calls Context.hideKeyboard
    hideKeyboard(currentFocus ?: View(this))
}

fun Context.hideKeyboard(view: View) {
    view.hideKeyboard()
}

Cómo mostrar un teclado suave

fun Context.showKeyboard() { // Or View.showKeyboard()
    val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}

Método más simple al solicitar simultáneamente el foco en un texto de edición

myEdittext.focus()

fun View.focus() {
    requestFocus()
    showKeyboard()
}

Simplificación de bonificación:

Elimine el requisito para usar siempre getSystemService: Biblioteca Splitties

// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)

361

En el AndroidManifest.xml:

<activity android:name="com.your.package.ActivityName"
          android:windowSoftInputMode="stateHidden"  />

o tratar

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)‌​;

Por favor verifique esto también


3
Gracias por android:windowSoftInputMode="stateHidden"
Shylendra Madda

2
En realidad, también hay una gran respuesta para evitar centrarse en la edición de texto stackoverflow.com/questions/4668210/…
Boris Treukhov

204

Use las siguientes funciones para mostrar / ocultar el teclado:

/**
 * Hides the soft keyboard
 */
public void hideSoftKeyboard() {
    if(getCurrentFocus()!=null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

/**
 * Shows the soft keyboard
 */
public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.showSoftInput(view, 0);
}

44
Context.INPUT_METHOD_SERVICE para aquellos que están en fragmentos o no están en la actividad principal, etc.
Oliver Dixon

77
Puedes probar esto. Funciona si lo llamas desde la actividad. getWindow (). setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) ‌;
Sinan Dizdarević

¿Qué pasa si necesitamos llamar a esto desde un oyente? Me gustaonFocusChange()
André Yuhai

44

Simplemente agregue dos atributos a la vista principal de editText.

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

36

Ponga esto en el manifiesto dentro de la etiqueta Actividad

  android:windowSoftInputMode="stateHidden"  

o android: windowSoftInputMode = "stateUnchanged": funciona así: no lo muestre si aún no se muestra, pero si estaba abierto al ingresar a la actividad, déjelo abierto).
Sujeet Kumar Gupta

ya tienes razón. pero ¿y si la orientación cambiara?
Saneesh

26

Prueba esto:

<activity
    ...
    android:windowSoftInputMode="stateHidden|adjustResize"
    ...
>

Mira este para más detalles.


14

Para ocultar el softkeyboard en el momento de inicio de actividad o Nueva onCreate(), onStart()etc se puede usar el siguiente código:

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

10

Usando AndroidManifest.xml

<activity android:name=".YourActivityName"
      android:windowSoftInputMode="stateHidden"  
 />

Usando Java

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

usando la solución anterior, el teclado se oculta pero el texto de edición no se enfoca cuando se crea la actividad, pero tómalo cuando los tocas usando:

agregar en su EditText

<EditText
android:focusable="false" />

también agregue el oyente de su EditText

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

7

Agregue el siguiente texto a su archivo xml.

<!--Dummy layout that gain focus -->
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:orientation="vertical" >
            </LinearLayout>

6

Espero que esto funcione, probé muchos métodos, pero este funcionó para mí fragments. solo ponga esta línea en onCreateview / init.

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

5

Para ocultar el teclado virtual en el momento del inicio de Nueva actividad o en el método onCreate (), onStart (), etc., use el siguiente código:

getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Para ocultar el teclado virtual en el momento del botón, haga clic en la actividad:

View view = this.getCurrentFocus();

    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

5

Use SOFT_INPUT_STATE_ALWAYS_HIDDEN en lugar de SOFT_INPUT_STATE_HIDDEN

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

5

agregue en su actividad en múltiples esta propiedad

android:windowSoftInputMode="stateHidden" 

4

Pon este código en tu archivo java y pasa el argumento para el objeto en edittext,

private void setHideSoftKeyboard(EditText editText){
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}

4

Puede configurar config en AndroidManifest.xml

Ejemplo:

<activity
    android:name="Activity"
    android:configChanges="orientation|keyboardHidden"
    android:theme="@*android:style/Theme.NoTitleBar"
    android:launchMode="singleTop"
    android:windowSoftInputMode="stateHidden"/>

4

Use el siguiente código para Ocultar el teclado virtual por primera vez cuando inicie la Actividad

getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_HIDDEN);

3

Prueba este también

Ed_Cat_Search = (EditText) findViewById(R.id.editText_Searc_Categories);

Ed_Cat_Search.setInputType(InputType.TYPE_NULL);

Ed_Cat_Search.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Ed_Cat_Search.setInputType(InputType.TYPE_CLASS_TEXT);
        Ed_Cat_Search.onTouchEvent(event); // call native handler
        return true; // consume touch even
    }
});

3

Las respuestas anteriores también son correctas. Solo quiero dar un resumen de que hay dos formas de ocultar el teclado al iniciar la actividad, desde manifest.xml. p.ej:

<activity
..........
android:windowSoftInputMode="stateHidden"
..........
/>
  • La forma anterior siempre lo oculta al ingresar a la actividad.

o

<activity
..........
android:windowSoftInputMode="stateUnchanged"
..........
/>
  • Este dice que no lo cambies (por ejemplo, no lo muestres si aún no se muestra, pero si estaba abierto al ingresar a la actividad, déjalo abierto).

2

Esto es lo que hice:

yourEditText.setCursorVisible(false); //This code is used when you do not want the cursor to be visible at startup
        yourEditText.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.onTouchEvent(event);   // handle the event first
                InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {

                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // hide the soft keyboard
                    yourEditText.setCursorVisible(true); //This is to display cursor when upon onTouch of Edittext
                }
                return true;
            }
        });

2

Si su aplicación está dirigida a Android API Level 21 o más, hay un método predeterminado disponible.

editTextObj.setShowSoftInputOnFocus(false);

Asegúrese de haber establecido el siguiente código en la EditTextetiqueta XML.

<EditText  
    ....
    android:enabled="true"
    android:focusable="true" />

1

Prueba esto.

Primero en su xml de búsqueda, los campos (nombre y pista, etc.) ponen @stringy no cadenas literales.

Luego onCreateOptionsMenu, el método debe tener un ComponentNameobjeto con el nombre del paquete y el nombre de la clase completa (con el nombre del paquete): en caso de que la actividad que tiene el SearchViewcomponente sea la misma que la de los resultados de búsqueda de usogetComponentName() , como dice el desarrollador de Google Android.

Probé muchas soluciones y después de mucho, mucho trabajo, esta solución me funciona.


1
Ed_Cat_Search = (EditText) findViewById(R.id.editText_Searc_Categories);

Ed_Cat_Search.setInputType(InputType.TYPE_NULL);

Ed_Cat_Search.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Ed_Cat_Search.setInputType(InputType.TYPE_CLASS_TEXT);
        Ed_Cat_Search.onTouchEvent(event); // call native handler
        return true; // consume touch even
    }
});

this one worked for me

1
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

funcionará


Si bien este código puede responder a la pregunta, proporcionar un contexto adicional con respecto a por qué y / o cómo este código responde a la pregunta mejora su valor a largo plazo.
rollstuhlfahrer
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.