Created
February 10, 2020 19:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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