Reputation: 213
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);
Upvotes: 8
Views: 7004
Reputation: 1
Honestly I've never had any luck with closing a keyboard from a fragment. I dont understand the engineering behind it but here is what works.
MainActivity-
public void closeKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
Fragment
private void closeKeyboard() {
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.closeKeyboard();
}
Then just call your method closeKeyboard() whereever you want in the Fragment
Upvotes: 0
Reputation: 359
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);
Upvotes: 16