How to hide soft keyboard on android after clicking outside EditText?

前端 未结 30 2304
醉话见心
醉话见心 2020-11-22 11:46

Ok everyone knows that to hide a keyboard you need to implement:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hi         


        
30条回答
  •  半阙折子戏
    2020-11-22 12:31

    I implemented dispatchTouchEvent in Activity to do this:

    private EditText mEditText;
    private Rect mRect = new Rect();
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        final int action = MotionEventCompat.getActionMasked(ev);
    
        int[] location = new int[2];
        mEditText.getLocationOnScreen(location);
        mRect.left = location[0];
        mRect.top = location[1];
        mRect.right = location[0] + mEditText.getWidth();
        mRect.bottom = location[1] + mEditText.getHeight();
    
        int x = (int) ev.getX();
        int y = (int) ev.getY();
    
        if (action == MotionEvent.ACTION_DOWN && !mRect.contains(x, y)) {
            InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            input.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(ev);
    }
    

    and I tested it, works perfect!

提交回复
热议问题