Skip to content

Instantly share code, notes, and snippets.

@gajerarajnit
Created August 22, 2017 06:10
Show Gist options
  • Save gajerarajnit/aa24f03a8acfca2b55985b36cfeecbb1 to your computer and use it in GitHub Desktop.
Save gajerarajnit/aa24f03a8acfca2b55985b36cfeecbb1 to your computer and use it in GitHub Desktop.
Close keyboard when touch outside of keyboard area.
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View view = getCurrentFocus();
if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
view.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + view.getLeft() - scrcoords[0];
float y = ev.getRawY() + view.getTop() - scrcoords[1];
if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
((InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
}
return super.dispatchTouchEvent(ev);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment