解决触摸Android屏幕的任何部分时隐藏软键盘的解决方案

问题描述

代码将帮助您隐藏键盘,使其与edittext以外的地方或仅在您的活动中编写此代码的任何地方都可以隐藏,或者您可以在项目的基本活动中编写。否则它也将键盘隐藏在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();
      }
    
   }

希望这有效!