Skip to content

Instantly share code, notes, and snippets.

@nightwolf738
Created June 3, 2021 23:03
Show Gist options
  • Save nightwolf738/7a112ee8492de3b559594aff57396662 to your computer and use it in GitHub Desktop.
Save nightwolf738/7a112ee8492de3b559594aff57396662 to your computer and use it in GitHub Desktop.
An extension function provided by Helios Alonso from Square
fun View.focusAndShowKeyboard() {
/**
* This is to be called when the window already has focus.
*/
fun View.showTheKeyboardNow() {
if (isFocused) {
post {
// We still post the call, just in case we are being notified of the windows focus
// but InputMethodManager didn't get properly setup yet.
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
requestFocus()
if (hasWindowFocus()) {
// No need to wait for the window to get focus.
showTheKeyboardNow()
} else {
// We need to wait until the window gets focus.
viewTreeObserver.addOnWindowFocusChangeListener(
object : ViewTreeObserver.OnWindowFocusChangeListener {
override fun onWindowFocusChanged(hasFocus: Boolean) {
// This notification will arrive just before the InputMethodManager gets set up.
if (hasFocus) {
[email protected]()
// It’s very important to remove this listener once we are done.
viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment