在 android 中触摸屏幕任何部分外部时隐藏软键盘的解决方案

Solution for hiding soft keyboard when touching outside of any part of screen in android

此代码将帮助您在编辑文本外部或任何地方隐藏触摸键盘,只需将此代码写入您的 activity 或者您可以在项目的基础 activity 中写入。或者它也会在 webview 中隐藏你的键盘。

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

此代码有助于隐藏键盘:

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

希望这有效!