-1

I use this method to hide keyboard.

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
View v = getActivity().getWindow().peekDecorView();
if (null != v) {
    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

But sometimes it is throwing NullPointerException, and the keyboard is n't hiding.

sync device with java.util.concurrent.CompletionException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object androidx.fragment.app.FragmentActivity.getSystemService(java.lang.String)' on a null object reference

I have save the activity instance by override method onAttach,and use

activity.getSystemService(INPUT_METHOD_SERVICE);

but it doesn't work.

littletable
  • 31
  • 1
  • 6

2 Answers2

0

Try this bunch of code:

To show the soft keyboard:

public void showSoftKeyboard(View view){
if(view.requestFocus()){
    InputMethodManager imm =(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT);
}

You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your edit field.

public void hideSoftKeyboard(View view){
  InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

From fragment or activity.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
A S M Sayem
  • 2,010
  • 2
  • 21
  • 28
0

to hide keyboard you can try : note : to get getSystemService you need have activity.

public static void hideSoftKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

}
TieuNhi
  • 29
  • 4