How to close Android Soft KeyBoard programmatically?

I am currently showing softkeyboard using the following code

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

And Here I d'not bind the softkeyboard with Edittext because of that I had used the above code.

Now I want to close the SoftKeyboard so i am currently using the below code but it is not working.

imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);

Can Anyone suggest me what to use for closing the softKeyboard ?


Based on Below Answer I want to let you clear that I am not using EditText, I use Layout on which I want to show Keyboard and Hide keyboard. I want to send keyboard key event to remote area bcoz of that I didnot used editText.


Solution 1:

I have tested and this is working:

...
//to show soft keyboard
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

//to hide it, call the method again
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

By the way, the second parameter of your code is not right, please have a look at here.

Solution 2:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EditTextName.getWindowToken(), 0);

Solution 3:

Use this working code :

InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Solution 4:

If you want, you can use entire class and call KeyboardUtil.hideKeyBoard(context) method wherever:

public class KeyboardUtil
{
public static void hideKeyboard(Activity activity)
    {
        try
        {
            InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
         }
        catch (Exception e)
        {
            // Ignore exceptions if any
                Log.e("KeyBoardUtil", e.toString(), e);
        }
    }
}