Dismiss keyboard when click outside of EditText in android

后端 未结 9 933
旧时难觅i
旧时难觅i 2021-02-01 05:31

I have an EditText called myTextview. I want the soft keyboard to show when I click on the EditText but then dismiss if I click outside of

9条回答
  •  臣服心动
    2021-02-01 05:53

    I found a better solution:

    Override the dispatchTouchEvent method in your Activity.

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

    This is applicable even if you are working with webview.

    UPDATE 10th July 2020

    The above method works perfectly but the EditText is still has the focus and typing cursor is still visible.

    To solve the described issue. Do this

    1. Add findViewById(android.R.id.content).setFocusableInTouchMode(true); in your onCreate() method

    2. Add findViewById(android.R.id.content).clearFocus(); in the hideKeyboard() method

    Credit to Eddwhis's comment

提交回复
热议问题