ab11
ab11

Reputation: 20090

Android: how to close explicitly displayed soft keyboard?

I am showing a dialog for textinput and would like to automatically display the soft keyboard if no hard keyboard is open. In order to get it to display on my Samsung Galaxy Tab, I had to use the SHOW_FORCED flag, the SHOW_IMPLICIT flag did not work. Also, on dialog dismissal I would like to close the keyboard if I forced its display. However, the code I'm using below does not close the keyboard on my Galaxy Tab; I assume it is because I used the Explicit flag to show.

    /* from the dialog constructor*/

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.restartInput(mEditText);

    //only display if there is no hard keyboard out 
    Configuration config = getResources().getConfiguration();
    if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES)
    {
      mForcedKeyboardDisplay = true;
      imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }


    /* from the onDismiss() method*/

    //if we previously forced keyboard display, force it to close
    if (mForcedKeyboardDisplay)
    {
       InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
       imm.restartInput(mEditText);

       imm.hideSoftInputFromWindow(mEditText.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
       //this doesn't work either 
       //imm.hideSoftInputFromWindow(mEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
       //nor does this
       //imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

Upvotes: 1

Views: 5409

Answers (1)

hackbod
hackbod

Reputation: 91331

First, don't use toggleSoftInput(). That does what it name says -- toggles the state of the IME. If you actually want it make sure it is shown, use showSoftInputFromWindow().

Second, there is no reason to call restartInput().

Calling showSoftInput() with a 0 flag is exactly what the framework does when you tap on a text view to show the IME. In fact here is the code: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/TextView.java

If you can get the IME to be shown by tapping on the text view, but your own call is not working, you really need to figure out why your call is not working. I would strongly recommend NOT using SHOW_FORCED -- that has somewhat special behavior, which I doubt you want. (For example if the user presses home the IME will stay open. Generally not desirable.)

The most likely reason for your call to hide the IME to not work is that your window doesn't have input focus at that point... you will probably see a message in the log if this is the case. In fact, be sure to look in the log anyway since often messages are printed when problems happen.

Upvotes: 5

Related Questions