Hide soft keyboard on losing focus

后端 未结 9 1265
-上瘾入骨i
-上瘾入骨i 2020-12-04 16:47

When we have an EditText and it loses focus (to an element that doesn\'t need a keyboard), should the soft keyboard hide automatically or are we supposed to hid

9条回答
  •  情歌与酒
    2020-12-04 17:09

    You can override the dispatchTouchEvent method to achieve it:

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
    
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
    
            /**
             * It gets into the above IF-BLOCK if anywhere the screen is touched.
             */
    
            View v = getCurrentFocus();
            if ( v instanceof EditText) {
    
    
                /**
                 * Now, it gets into the above IF-BLOCK if an EditText is already in focus, and you tap somewhere else
                 * to take the focus away from that particular EditText. It could have 2 cases after tapping:
                 * 1. No EditText has focus
                 * 2. Focus is just shifted to the other EditText
                 */
    
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                    v.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent( event );
    }
    

    Bonus: In case of an EditText gaining focus, the order of event triggered is:

    1. onFocusChange() of another EditText is called (if that other edittext is losing focus)
    2. ACTION_DOWN is called
    3. Finally, onFocusChange() method of that EditText will get called.

提交回复
热议问题