Lalit Jadiya
Lalit Jadiya

Reputation: 213

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

Upvotes: 8

Views: 7004

Answers (2)

Stephen Louks
Stephen Louks

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

Firass Obaid
Firass Obaid

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

Related Questions