Android点击除edittext外其他区域或控件隐藏软键盘

我在开发过程中,自定义了一个dialog用来填写一些信息,但是此时遇到了问题,我想实现在点击确定或取消按钮时使软键盘消失,所以我在确定和取消的监听方法中设置了一下属性

InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
此时我的AndroidManifest.xml中对应的activity中设置了如下属性

android:windowSoftInputMode="stateHidden|adjustPan"
但是当我点击对话框的取消时,会关闭当前输入对话框,但是界面还会显示一个对话框,我尝试使用了各种方法,但是最终都没有实现想要的效果

经过我在网上资料的搜集和尝试,发现可以使用以下两个方法,实现想要的效果

public static boolean isShouldHideInput(View v, MotionEvent event) {
    if (v != null && (v instanceof EditText)) {
        int[] leftTop = {0, 0};
        //获取输入框当前的location位置
        v.getLocationInWindow(leftTop);
        int left = leftTop[0];
        int top = leftTop[1];
        int bottom = top + v.getHeight();
        int right = left + v.getWidth();
        if (event.getX() > left && event.getX() < right
                && event.getY() > top && event.getY() < bottom) {
            // 点击的是输入框区域,保留点击EditText的事件
            return false;
        } else {
            return true;
        }
    }
    return false;
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (ScreenUtils.isShouldHideInput(v, ev)) {

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    // 必不可少,否则所有的组件都不会有TouchEvent    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}
记得AndroidManifest.xml中不要设置
android:windowSoftInputMode="stateHidden|adjustPan"

猜你喜欢

转载自blog.csdn.net/u014172743/article/details/50748097