Android拦截点击事件,实现点击任何地方关闭输入框,键盘关闭时隐藏光标

原创
2017/02/07 14:56
阅读数 123

Activity 声明输入键盘默认隐藏 

     getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        LogC.i("touch action");

        //don't click on edit text then hide keyboard and hide cursor
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            LogC.i("touch action up");
            View currentFocus = getCurrentFocus();
            if (currentFocus != null) {
                boolean pressed = currentFocus.isPressed();
                //don't click on edit text
                if (currentFocus instanceof EditText && !pressed) {
                    hideSoftKeyboard();
                    getWindow().getDecorView().requestFocus();
                    ((EditText) currentFocus).setCursorVisible(false);
                    LogC.i("touch action clear focus");
                }
            }
        }
        boolean b = super.dispatchTouchEvent(ev);

        //focus is newest after dispatch event
        //click on edit text then show keyboard and show cursor
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View currentFocus = getCurrentFocus();
            if (currentFocus != null) {
                boolean pressed = currentFocus.isPressed();
                //click on edit text
                if (currentFocus instanceof EditText && pressed) {
                    ((EditText) currentFocus).setCursorVisible(true);
                }
            }
        }
        return b;
    }

protected void hideSoftKeyboard() {
        if (this.getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
    }

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部