Hide soft keyboard on losing focus

后端 未结 9 1288
-上瘾入骨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:10

    Try this

     /**
     * Hide keyboard on touch of UI
     */
    public void hideKeyboard(View view) {
    
        if (view instanceof ViewGroup) {
    
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
    
                View innerView = ((ViewGroup) view).getChildAt(i);
    
                hideKeyboard(innerView);
            }
        }
        if (!(view instanceof EditText)) {
    
            view.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard(v);
                    return false;
                }
    
            });
        }
    
    }
    
    /**
     * Hide keyboard while focus is moved
     */
    public void hideSoftKeyboard(View view) {
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) contentsContext_
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputManager != null) {
                if (android.os.Build.VERSION.SDK_INT < 11) {
                    inputManager.hideSoftInputFromWindow(view.getWindowToken(),
                            0);
                } else {
                    if (this.getCurrentFocus() != null) {
                        inputManager.hideSoftInputFromWindow(this
                                .getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    view.clearFocus();
                }
                view.clearFocus();
            }
        }
    }
    

提交回复
热议问题