Abrir el teclado de software mediante programación


Tengo una actividad sin widgets secundarios para ella y el archivo xml correspondiente es,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
>
</LinearLayout>

Y quiero abrir el teclado de software mediante programación mientras se inicia la actividad.y lo que he intentado hasta ahora es,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

Dame alguna guía.

Author: NightFury, 2011-04-08

18 answers

He utilizado las siguientes líneas para mostrar el teclado de software manualmente dentro del evento onclick, y el teclado está visible.

InputMethodManager inputMethodManager =
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
    linearLayout.getApplicationWindowToken(),
    InputMethodManager.SHOW_FORCED, 0);

Pero todavía no puedo abrir esto mientras se abre la actividad, así que ¿hay alguna solución para esto?

 134
Author: Vignesh,
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-12-01 08:14:37

En su archivo de manifiesto, intente agregar lo siguiente al <activity> que desea mostrar el teclado cuando comience la actividad:

android:windowSoftInputMode="stateVisible"

Esto debería hacer que el teclado se vuelva visible cuando se inicie la actividad.

Para obtener más opciones, consulte la documentación .

 110
Author: jemerick,
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-10-13 14:15:23

Por favor, siga el siguiente código. Estoy seguro de que su problema se resolverá.

if (imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
   } 
 31
Author: AndroidDanger,
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-12-17 04:39:51

Esto es obras

<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

O

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
 23
Author: ahtartam,
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-06 01:29:15

Todo lo que necesitaba era exponer el teclado, en un momento muy preciso. Esto funcionó para mí! Gracias Benites.

    private Handler mHandler= new Handler();

Y en el momento preciso:

    mHandler.post(
    new Runnable() {
        public void run() {
            InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
            yourEditText.requestFocus();
        }
    }); 
 15
Author: DiegoSoto,
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-24 07:16:20

He utilizado las siguientes líneas para mostrar el teclado de software manualmente dentro del evento onclick.

public void showKeyboard(final EmojiconEditText ettext){
          ettext.requestFocus();
          ettext.postDelayed(new Runnable(){
            @Override public void run(){
              InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
              keyboard.showSoftInput(ettext,0);
            }
          }
        ,200);
        }
 11
Author: Ram,
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-09 10:28:05

Pon eso en el método onResume:

findViewById(R.id.root_view_of_your_activity_layout).post(
new Runnable() {
    public void run() {
        InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(),     InputMethodManager.SHOW_FORCED, 0);
        yourEditText.requestFocus();
    }
});

El ejecutable es necesario porque cuando el sistema operativo dispara el método onResume no puede estar seguro de que todas las vistas se dibujen, por lo que el método post llamado desde su diseño raíz lo hace esperar hasta que todas las vistas estén listas.

 9
Author: Benites,
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-19 14:57:35

In onCreate method of activity or onActivityCreated of a fragment

....
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.removeOnPreDrawListener(this);
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

            // !Pay attention to return `true`
            // Chet Haase told to 
            return true;
        }
    });
 8
Author: Alex,
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-12-06 09:36:44

Parece que esto está funcionando

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patientid);

        editText = (EditText)findViewById(R.id.selectPatient);
        //editText.requestFocus(); //works without that

    }

@Override
    protected void onResume() {

        findViewById(R.id.selectPatient).postDelayed(
        new Runnable() {
            public void run() {
                 editText.requestFocus();
                InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT);
            }
        },100);
        super.onResume();
    }

Parece que esto funciona mejor: en manifiesto:

<application>
    <activity
        android:name="com.doodkin.myapp.ReportActivity"
        android:label="@string/title_activity_report"
        android:screenOrientation="sensor" 
        android:windowSoftInputMode="stateHidden" > // add this or stateVisible
    </activity>
</application>

Parece que el manifiesto funciona en Android 4.2.2 pero no funciona en android 4.0.3

 7
Author: Shimon Doodkin,
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-21 19:08:34

He utilizado de esta manera para mostrar el teclado de software de forma programática y esto funciona para mí para evitar el cambio de tamaño automático de la pantalla al iniciar el teclado.

En manifiesto:

<activity android:name="XXXActivity" android:windowSoftInputMode="adjustPan">
</activity>

En Xxxactividad:

EditText et =  (EditText))findViewById(R.id.edit_text);  
  Timer timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInputFromWindow(et.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);

                }
            };
            timer.schedule(task, 200);

Asumo que esto ahorrará a otros tiempo para buscar este problema.

 6
Author: Noundla,
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-14 13:30:26
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
 3
Author: Kai Wang,
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-01-29 16:07:17

Este es el código fuente requerido:

public static void openKeypad(final Context context, final View v) 
 {
new Handler().postDelayed(new Runnable() 
{
    @Override
    public void run() 
    {
        InputMethodManager inputManager =   (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);    
        Log.e("openKeypad", "Inside Handler");
    }
},300);}

Para más detalles , por favor vaya a través de este enlace. Esto me ayudó. https://github.com/Nikhillosalka/Keyboard/blob/master/README.md

 1
Author: Nikhil Losalka,
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-29 13:14:24

Similar a la respuesta de @ShimonDoodkin esto es lo que hice en un fragmento.

Https://stackoverflow.com/a/29229865/2413303

    passwordInput.postDelayed(new ShowKeyboard(), 300); //250 sometimes doesn't run if returning from LockScreen

Donde ShowKeyboard es

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
        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);
 1
Author: EpicPandaForce,
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-09-01 15:34:03

Lo usé como singleton como:

public static void showSoftKeyboard(final Context context, final EditText editText) {
        try {
            editText.requestFocus();
            editText.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                            keyboard.showSoftInput(editText, 0);
                        }
                    }
                    , 200);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Úsalo en tu actividad como:

showSoftKeyboard(this, yourEditTextToFocus);
 1
Author: Shylendra Madda,
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-12-01 07:21:00

Ya Hay demasiadas respuestas, pero nada funcionó para mí aparte de esto

inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);

Usé showSoftInput con SHOW_FORCED

Y mi actividad tiene

 android:windowSoftInputMode="stateVisible|adjustResize"

Espero que esto ayude a alguien

 0
Author: spaceMonkey,
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-05 15:43:34
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Use el código anterior en onResume () para abrir el teclado de software

 0
Author: Sanket Parchande,
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-06-29 11:28:42

Publique este método en su actividad base y úselo otras actividades como un encanto

public void openKeyboard() {
    InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }
}
 0
Author: Ajay Chauhan,
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-17 16:29:18

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);
}
 0
Author: Khemraj,
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-01 10:00:32