0

I am trying to hide keyboard after selecting an item from Spinner but the code is not working and nothing happens. But in other side the same code works in normal fragment.

Here is the method to hide keyboard:

public static void hideKeypad(Activity activity) {
    View view = activity.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
Auguste
  • 2,007
  • 2
  • 17
  • 25

2 Answers2

0

This is working for me in a fragment

    public void removePhoneKeypad() {
    if(getActivity().getCurrentFocus()!=null &&getActivity().getCurrentFocus().getWindowToken() != null) {
        System.out.println("getCurrentFocus() in frag");
        InputMethodManager inputManager = (InputMethodManager) rootView
                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        IBinder binder = getActivity().getCurrentFocus().getWindowToken();
        inputManager.hideSoftInputFromWindow(binder,
                InputMethodManager.HIDE_NOT_ALWAYS);
    }
    getActivity().getWindow().setSoftInputMode(
              WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
Prashanth Debbadwar
  • 1,047
  • 18
  • 33
0

You need to specify the rootView of the Fragment because in your method it's see the getCurrentFocus() == null, So it will never go to the rest of the code.

This is the right code:

public static void hideKeypad(Activity activity, View view) {
if (view != null) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
   }
}

Make a class variable View and equal it with the rootView of the Fragment in the onCreateView() and use this method anywhere in this Fragment.

Mohamed
  • 656
  • 9
  • 28