Hide keyboard when user taps anywhere else on the screen
suggest changeAdd code in your Activity.
This would work for Fragment also, no need to add this code in Fragment.
@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();
float y = ev.getRawY();
if (x < scrcoords[0] || x > scrcoords[0] + view.getWidth()
|| y < scrcoords[1] || y > scrcoords[1] + view.getHeight()) {
((InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents