Pregunta

Estoy mostrando un cuadro de entrada utilizando AlertDialog. El EditText dentro del propio diálogo se enfoca automáticamente cuando llamo AlertDialog.show(), pero el teclado virtual no se muestra automáticamente.

¿Cómo hago el teclado en pantalla mostrará de forma automática cuando se muestre el diálogo? (Y no hay teclado físico / hardware). Similar a la forma cuando se presiona el botón de búsqueda para invocar la búsqueda global, el teclado en pantalla se muestra automáticamente.

¿Fue útil?

Solución

Puede crear un oyente enfoque en el EditText en el AlertDialog, a continuación, obtener AlertDialog del Window. Desde allí se puede hacer el espectáculo teclado de software llamando setSoftInputMode.

final AlertDialog dialog = ...;

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

Otros consejos

Para mostrar el uso del teclado:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Para ocultar el uso del teclado:

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

Puede solicitar un teclado de función derecha después de crear el cuadro de diálogo (prueba en SDK - r20)

// create dialog
final AlertDialog dialog = ...; 

// request keyboard   
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Yo tenía el mismo problema y lo resolvió con el siguiente código. No estoy seguro de cómo se comportará en un teléfono con teclado de hardware.

// TextEdit
final EditText textEdit = new EditText(this);

// Builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String text = textEdit.getText().toString();
        finish();
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

// Dialog
AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
    }
});

dialog.show();

he encontrado este ejemplo http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html . Agregue el siguiente código justo antes de alert.show().

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

o

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

Fragmentos de código de las otras respuestas funciona, pero no siempre es obvio dónde colocarlos en el código, especialmente si está utilizando una AlertDialog.Builder y siguieron al oficial tutorial de diálogo porque no utiliza final AlertDialog ... o alertDialog.show().

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

Es preferible

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Debido SOFT_INPUT_STATE_ALWAYS_VISIBLE, se oculta el teclado si el foco cambia de distancia del EditarTexto, donde SHOW_FORCED mantendrá el teclado en pantalla hasta que es despedido de forma explícita, incluso si el usuario vuelve a la pantalla de inicio o muestra las aplicaciones recientes.

código siguiente es trabajar para una AlertDialog creado usando un diseño personalizado con un EditarTexto definido en XML. También establece el teclado para tener un "Go" clave y permite que active el botón positivo.

alert_dialog.xml:

<RelativeLayout
android:id="@+id/dialogRelativeLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <!-- android:imeOptions="actionGo" sets the keyboard to have a "go" key instead of a "new line" key. -->
    <!-- android:inputType="textUri" disables spell check in the EditText and changes the "go" key from a check mark to an arrow. -->
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:imeOptions="actionGo"
        android:inputType="textUri"/>

</RelativeLayout>

AlertDialog.java:

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

public class CreateDialog extends AppCompatDialogFragment {
    // The public interface is used to send information back to the activity that called CreateDialog.
    public interface CreateDialogListener {
        void onCreateDialogCancel(DialogFragment dialog);    
        void onCreateDialogOK(DialogFragment dialog);
    }

    CreateDialogListener mListener;

    // Check to make sure that the activity that called CreateDialog implements both listeners.
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (CreateDialogListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement CreateDialogListener.");
        }
    }

    // onCreateDialog requires @NonNull.
    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        LayoutInflater customDialogInflater = getActivity().getLayoutInflater();

        // Setup dialogBuilder.
        alertDialogBuilder.setTitle(R.string.title);
        alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null));
        alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogCancel(CreateDialog.this);
            }
        });
        alertDialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogOK(CreateDialog.this);
            }
        });

        // Assign the resulting built dialog to an AlertDialog.
        final AlertDialog alertDialog = alertDialogBuilder.create();

        // Show the keyboard when the dialog is displayed on the screen.
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // We need to show alertDialog before we can setOnKeyListener below.
        alertDialog.show();

        EditText editText = (EditText) alertDialog.findViewById(R.id.editText);

        // Allow the "enter" key on the keyboard to execute "OK".
        editText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button, select the PositiveButton "OK".
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Trigger the create listener.
                    mListener.onCreateDialogOK(CreateDialog.this);

                    // Manually dismiss alertDialog.
                    alertDialog.dismiss();

                    // Consume the event.
                    return true;
                } else {
                    // If any other key was pressed, do not consume the event.
                    return false;
                }
            }
        });

        // onCreateDialog requires the return of an AlertDialog.
        return alertDialog;
    }
}

Bueno, este es un post bastante viejo, todavía hay algo que añadir
Estos 2 métodos sencillos que me ayudan a mantener bajo control del teclado y trabajan simplemente perfecto:.

Mostrar teclado

public void showKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.showSoftInput(v, 0);
}

Ocultar teclado

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

Me permito indicar algo de información adicional para la solución de yuku, porque me pareció difícil de conseguir este trabajo! ¿Cómo consigo el objeto de mi AlertDialog AlertDialog.Builder? Bueno, es el resultado de mi ejecución alert.show():

final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
alert.setView(input);

// do what you need, like setting positive and negative buttons...

final AlertDialog dialog = alert.show();

input.setOnFocusChangeListener(new OnFocusChangeListener() {
   @Override
   public void onFocusChange(View v, boolean hasFocus) {
      if(hasFocus) {
         dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
      }
   }
});

Tome un vistazo a esta discusión que se ocupa de cómo mostrar y ocultar el IME manualmente. Sin embargo, mi sensación es que si un EditText centrado no es lo que el IME arriba es porque se está llamando AlertDialog.show() en su OnCreate() o algún otro método que es evocada antes de que realmente se presenta la pantalla. Moverlo a OnPostResume() debe fijarlo en ese caso creo.

Sí se puede hacer con setOnFocusChangeListener que le ayudará.

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

Si alguien está recibiendo:

  
    

No se puede hacer una referencia estática al método getSystemService no estático (String) de la Tipo de la actividad

  

Trate de añadir Contexto a la llamada getSystemService.

Entonces

InputMethodManager imm = 
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

La pregunta original se refiere a diálogos y mi EditarTexto es en una vista normal. De todos modos, sospecho que esto debería funcionar para la mayoría de ustedes también. Así que aquí es lo que funciona para mí (el método de mayor audiencia se sugirió anteriormente hizo nada para mí). He aquí una EditView a medida que hace esto (subclasificación no es necesario, pero he encontrado que es conveniente para mis propósitos, ya que quería coger también el foco cuando la vista se hace visible).

Esto es en realidad en gran parte los mismos que los tidbecks responder. En realidad no se dio cuenta de su respuesta en absoluto, ya que tenía cero hasta votos. Entonces yo estaba a punto de comentar simplemente su puesto, pero habría sido demasiado largo, así que terminé haciendo este post de todos modos. tidbeck señala que él está seguro de cómo funciona con dispositivos que tienen teclados. Puedo confirmar que el comportamiento parece ser exactamente el mismo en ambos casos. Eso es tal que en el modo de retrato del teclado de software se eleve y que el paisaje no es así. Tener el teclado físico se deslizó fuera o no hace ninguna diferencia en mi teléfono.

Porque, Yo he encontrado el comportamiento un poco incómodo que optó por usar: InputMethodManager.SHOW_FORCED. Esto funciona como quería que funcione. El teclado se hace visible independientemente de la orientación, sin embargo, al menos en mi dispositivo que no se eleva si el teclado de hardware se ha deslizado hacia fuera.

import android.app.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class BringOutTheSoftInputOnFocusEditTextView extends EditText {

    protected InputMethodManager inputMethodManager;

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BringOutTheSoftInputOnFocusEditTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
        this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED);
                }
            }
        });
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.VISIBLE) {
            BringOutTheSoftInputOnFocusEditTextView.this.requestFocus();
        }
    }

}

El problema parece ser que desde el lugar donde se introduce el texto que está oculto inicialmente (o anidado o algo así), AlertDialog está fijando automáticamente el WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM bandera o WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE para que las cosas no desencadenan una entrada suave en aparecer.

La forma en que solucionar este problema es añadir lo siguiente:

(...)
// Create the dialog and show it
Dialog dialog = builder.create()
dialog.show();

// After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Trate de usar:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

Para mostrar el teclado, para mí, tenía que hacer lo siguiente

Android TextField: establecer el foco de entrada de software + programación

Esencialmente, la solución es la siguiente

@Override
public void onResume() {
    super.onResume();
    //passwordInput.requestFocus(); <-- that doesn't work
    passwordInput.postDelayed(new ShowKeyboard(), 325); //250 sometimes doesn't run if returning from LockScreen
}

¿Dónde está ShowKeyboard

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
        //passwordInput.requestFocusFromTouch(); //this gives touch event to launcher in background -_-
        passwordInput.requestFocus();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
    }
}

Después de una entrada exitosa, también me aseguro de ocultar el teclado

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);

Ponga estos métodos en su clase Util y usar en cualquier lugar.

Kotlin

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}

creé funciones de extensión agradable Kotlin-esqe en caso que alguien está interesado

fun Activity.hideKeyBoard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun Activity.showKeyboard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Esta es una buena muestra para usted:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollID"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="true"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:weightSum="1" >

        <EditText
            android:id="@+id/txtInpuConversation"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:hint="@string/edt_Conversation" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/btn_Conversation" />
    </LinearLayout>

</LinearLayout>

¿Por qué esta respuesta - Debido solución anterior se mostrará el teclado pero no va a desaparecer si hace clic en cualquier otra que EditText. Así que hay que hacer algo para que la keybaord desaparecer cuando EditText pierde el foco.

Usted puede lograr esto haciendo los siguientes pasos:

  1. Hacer la vista padre (ver el contenido de su actividad) se puede hacer clic y enfocable mediante la adición de los siguientes atributos

        android:clickable="true" 
        android:focusableInTouchMode="true" 
    
  2. Implementar un método hideKeyboard ()

        public void hideKeyboard(View view) {
            InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY );
        }
    
  3. Por último, establezca la onFocusChangeListener de su EditarTexto.

        edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    

Esto es poco complicado. Lo hice de esta manera y funcionó.

1.At primera llamada para ocultar la entrada suave de la ventana. Esto ocultará la entrada suave si el teclado en pantalla es visible o no hacer nada si no lo es.

2.Show su cuadro de diálogo

3.Then simplemente llame para cambiar de entrada de software.

código:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind‌​owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);

Probar

  

SomeUtils.java

public static void showKeyboard(Activity activity, boolean show) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

    if(show)
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
    else
        inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
}

probado muchos, pero esto es lo que funcionó para mí (Kotlin):

        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()

En cuanto a https://stackoverflow.com/a/39144104/2914140 Me simplificado un poco:

// In onCreateView():
view.edit_text.run {
    requestFocus()
    post { showKeyboard(this) }
}

fun showKeyboard(view: View) {
    val imm = view.context.getSystemService(
        Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Es mejor que https://stackoverflow.com/a/11155404/2914140 :

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

porque cuando se pulsa el botón de inicio y pasar a la pantalla principal, el teclado permanecerá abierta.

Sé que esta pregunta es viejo por Creo utilizando una función de extensión es una forma más bonita para mostrar el teclado para una edición de texto

aquí es el método que utilizo para mostrar el teclado para una EditarTexto.

código Kotlin: sólo tiene que llamar edittext.showKeyboard()

fun EditText.showKeyboard() {
  post {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }
}

el código de Java:

public static void showKeyboard(EditText editText) {
    editText.post(new Runnable() {
      @Override
      public void run() {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
      }
    });
  }
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

A esto lo llamo en onCreate () para mostrar el teclado de forma automática, cuando entré en la actividad.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top