Skip to content

Instantly share code, notes, and snippets.

@vklachkov
Created February 10, 2020 19:43
Show Gist options
  • Save vklachkov/8b3f293d3d02e7070cca0a188182894d to your computer and use it in GitHub Desktop.
Save vklachkov/8b3f293d3d02e7070cca0a188182894d to your computer and use it in GitHub Desktop.
Removing focus from the input field automatically when you click in any other area
// Put it in your Activity and it'll apply to all EditTexts including those within fragments within that activity
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
v.clearFocus()
val imm: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
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