TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Controlling the Soft Keyboard during onClick - Android

I had an issue where if user was typing and hit submit, the keyboard would not go away, so I found this code to fix that issue (by placing this in the onClick method):

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

However, if the user manually closed the keyboard, then clicked submit, I found the code above would bring the keyboard back -- not good.

The question:

Is there better code to use? OR can I just say something like =

 if (keyboard = displayed) {
            // do code above
          } else { 
            // do nothing 
          }

Upvotes: 2

Views: 2643

Answers (1)

almalkawi
almalkawi

Reputation: 1118

To hide the keyboard:

final InputMethodManager inputMethodManager =
            (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

To show it:

final InputMethodManager inputMethodManager =
            (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);

Upvotes: 6

Related Questions