1

This code will help you to hide keyboard in touch of outside the edittext or anywhere just write this code in your activity or you can write in base activity of your project. Or it will also hide your keyboard in webview also.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText &&
            !v.getClass().getName().startsWith("android.webkit.")) {
        int[] sourceCoordinates = new int[2];
        v.getLocationOnScreen(sourceCoordinates);
        float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
        float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
            hideKeyboard(this);
        }

    }
    return super.dispatchTouchEvent(ev);
}

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

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

  • Does this answer your question? [How do you close/hide the Android soft keyboard using Java?](https://stackoverflow.com/questions/1109022/how-do-you-close-hide-the-android-soft-keyboard-using-java) – Abhimanyu Nov 03 '20 at 12:12
  • Actually I posted the answer of the problem which is just found after searching a lot. Basically it will automatically hide the keyboard whenever user touch anywhere in the screen except edit text. – PINTOO AGGARWAL Nov 03 '20 at 13:35

1 Answers1

1

This code helps to hide the keyboard:

public static void hideSoftKeyboard(Activity activity){
   try{
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(
                getCurrentFocus().getWindowToken(),
                0
        );
      }catch(Exception e){
         e.printStackTrace();
      }
    
   }

hope this works!