欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android点击EditText控件外部隐藏键盘

程序员文章站 2022-08-19 17:12:52
//根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘private boolean isShouldHideKeyboard(View v, MotionEvent event) { if (v instanceof EditText) { int[] l = {0, 0}; v.getLocationInWindow(l); int left = l[0], top = l[1], botto....
//根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
    if (v instanceof EditText) {
        int[] l = {0, 0};
        v.getLocationInWindow(l);
        int left = l[0],
        top = l[1],
        bottom = top + v.getHeight(),
        right = left + v.getWidth();
        return !(event.getX() > left && event.getX() < right
                && event.getY() > top && event.getY() < bottom);
    }
    return false;
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (isShouldHideKeyboard(v, ev)) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if(imm != null){     
           imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    return super.dispatchTouchEvent(ev);
}

本文地址:https://blog.csdn.net/c_furong/article/details/108850622