Search code examples
androidkeyboard

Hiding Keypad within Fragment


I am getting these errors when trying to hide the keyboard inside a fragment within an activity:

Error: Cannot resolve getSystemService

Cannot resolve Context

Cannot resolve getCurrentFocus()

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

Solution

  • Inside a fragment you should use getActivity(),

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