how to hide soft keyboard in fragments?

Viewed 6608

i want to hide keyboard in fragments in android.Because once it displays it remain visible in all fragments.I try this method

    public static void hideKeyboard(Context ctx) {
    InputMethodManager inputManager = (InputMethodManager) ctx
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    // check if no view has focus:
    View v = ((Activity) ctx).getCurrentFocus();
    if (v == null)
        return;

    inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

and call this method on button click

signIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                hideKeyboard(ctx);
                login();


        }
    });

but this give error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference"

5 Answers

Use this for kotlin users create a file and add this code

fun hideSoftKeyboard(activity: Activity) {
    if (activity.currentFocus == null) {
        return
    }
    val inputMethodManager =
        activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(activity.currentFocus!!.windowToken, 0)
}

Now call this method anywhere using

hideSoftKeyboard(requireActivity())

Happy coding..NB for kotlin

Hide it using the window token from your fragment view

For Kotlin -

if (activity != null){
    // Hide soft keyboard
    val imm =
        activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(requireView().windowToken, 0)
}
Related