Akshay J
Akshay J

Reputation: 5458

Android: Hide keyboard on button press

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.

Upvotes: 0

Views: 82

Answers (3)

matip
matip

Reputation: 890

Try:

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

Upvotes: 0

Rissmon Suresh
Rissmon Suresh

Reputation: 14053

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);
}

Upvotes: 1

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);

Upvotes: 0

Related Questions