0

My main activity has 2 EditText (username and password) and a Button (login). I am displaying the status below the button.

As the user clicks the button, I need to hide the keyboard, otherwise the keyboad would come infront of status messages.

So in the login button's click event I am programatically closing the keyboard using the following code:

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

I believe the above code if for toggling the keyboard state and not specifically for closing it.

Now the problem is that if the keyboard is already collapsed and the user clicks the button, it shows the keyboard.

I need an alternative of the above code which will check if the keyboard is closed and if closed open it.

Akshay J
  • 4,957
  • 11
  • 61
  • 100

3 Answers3

1

checkout below code

/**
 * 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);
}
Samuel Robert
  • 7,119
  • 7
  • 34
  • 52
Rissmon Suresh
  • 8,535
  • 5
  • 26
  • 33
0

Try this:

 public static final void hideKeyboard(View view, Context context) {
    InputMethodManager inputMethodManager =(InputMethodManager)context.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

In view send your button:

hideKeyboard(mButtonTest,context);
0

Try:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
matip
  • 704
  • 1
  • 7
  • 22