Android点击EditText控件外部隐藏键盘 Love The Way You Lie 2022-12-11 04:27 148阅读 0赞 //根据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); }
还没有评论,来说两句吧...