Created
February 6, 2020 14:30
-
-
Save ilfuriano/31e7a965cbf979c1f7ac6294a0c69200 to your computer and use it in GitHub Desktop.
Clear focus for EditText on click outside
This file contains hidden or 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
class MainActivity : AppCompatActivity() { | |
// code | |
// Clear focus for EditText on click outside | |
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { | |
if (ev?.action == MotionEvent.ACTION_DOWN) { | |
(currentFocus as? EditText)?.let { et -> | |
Rect().also { rect -> | |
et.getGlobalVisibleRect(rect) | |
if (!rect.contains(ev.rawX.toInt(), ev.rawY.toInt())) { | |
et.clearFocus() | |
et.hideKeyboad() | |
} | |
} | |
} | |
} | |
return super.dispatchTouchEvent(ev) | |
} | |
} | |
fun View.hideKeyboad() = | |
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(windowToken, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kotlin version of https://gist.github.com/sc0rch/7c982999e5821e6338c25390f50d2993