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

前端 未结 30 2111
醉话见心
醉话见心 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:12

    Well I manage to somewhat solve the problem, I overrode the dispatchTouchEvent on my activity, there I am using the following to hide the keyboard.

     /**
     * Called to process touch screen events. 
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                touchDownTime = SystemClock.elapsedRealtime();
                break;
    
            case MotionEvent.ACTION_UP:
                //to avoid drag events
                if (SystemClock.elapsedRealtime() - touchDownTime <= 150){  
    
                    EditText[] textFields = this.getFields();
                    if(textFields != null && textFields.length > 0){
    
                        boolean clickIsOutsideEditTexts = true;
    
                        for(EditText field : textFields){
                            if(isPointInsideView(ev.getRawX(), ev.getRawY(), field)){
                                clickIsOutsideEditTexts = false;
                                break;
                            }
                        }
    
                        if(clickIsOutsideEditTexts){
                            this.hideSoftKeyboard();
                        }               
                    } else {
                        this.hideSoftKeyboard();
                    }
                }
                break;
        }
    
        return super.dispatchTouchEvent(ev);
    }
    

    EDIT: The getFields() method is just a method that returns an array with the textfields in the view. To avoid creating this array on every touch, I created an static array called sFields, which is returned at the getFields() method. This array is initialized on the onStart() methods such as:

    sFields = new EditText[] {mUserField, mPasswordField};


    It is not perfect, The drag event time is only based on heuristics so sometimes it doesnt hide when performing long clics, and I also finished by creating a method to get all the editTexts per view; else the keyboard would hide and show when clicking other EditText.

    Still, cleaner and shorter solutions are welcome

提交回复
热议问题