Skip to content

Instantly share code, notes, and snippets.

@ahmmedrejowan
Created May 31, 2023 11:14
Show Gist options
  • Save ahmmedrejowan/bfff3db3865190def06cc27bdeb1e3da to your computer and use it in GitHub Desktop.
Save ahmmedrejowan/bfff3db3865190def06cc27bdeb1e3da to your computer and use it in GitHub Desktop.
Use this to hide keyboard and remove focus when touched outside of EditText
@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.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(event);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment