Skip to content

Instantly share code, notes, and snippets.

@BeokBeok
Last active May 5, 2020 14:43
Show Gist options
  • Save BeokBeok/4cd85378a0af3ae8244176e7ef4a2365 to your computer and use it in GitHub Desktop.
Save BeokBeok/4cd85378a0af3ae8244176e7ef4a2365 to your computer and use it in GitHub Desktop.
키패드를 보여주는 extension 함수
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) {
this@focusAndShowKeyboard.showTheKeyboardNow()
// 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