Android点击空白处关闭软键盘

Android点击空白处关闭软键盘

答案

直接说解决方法,在Activity中重写dispatchTouchEvent(MotionEvent ev)方法

/**
 * 点击空白处,关闭软键盘
 *
 * @param event event
 * @return boolean Return true if this event was consumed.
 */
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                v.setFocusable(false);
                v.setFocusableInTouchMode(true);

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

原理:在当前焦点在EditText的情况下,点击的不是该EditText所在区域,则关闭软键盘

另外的方法

监听整个根布局MotionEvent,当然效果没有上面这个方法好


   转载规则


《Android点击空白处关闭软键盘》 Mycroft Wong 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
hexo添加category目录 hexo添加category目录
hexo添加category目录一开始我以为直接在配置文件_config.yml中去掉注释categories即可,这样是不对的,还需要手动建立categories目录 新建categories目录使用命令hexo new page cat
2019-08-09
下一篇 
nginx配置多个域名 nginx配置多个域名
nginx配置多个域名新建了这个blog,同时上传了github和gitee,另外想发布到个人阿里云服务器,在阿里云服务器上直接拉取github仓库。 目标在不更改原来请求的情况下,添加二级域名blog,转发请求到博客文件夹。 nginx配
2019-08-09
  目录