Created
June 3, 2021 23:38
-
-
Save nightwolf738/92a56cb014cdd7b71fb97be1207bea57 to your computer and use it in GitHub Desktop.
My final solution to show Android keyboard thanks to Helios Alonso and Square team
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
fun View.focusAndShowKeyboard(tryAgain: Boolean = true) { | |
/** | |
* 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 | |
val isInputMethodManagerSetup = imm.showSoftInput(this, SHOW_IMPLICIT) | |
if (!isInputMethodManagerSetup) { | |
// InputMethodManager still didn't get properly setup yet even we post the call. | |
// so we should give it one more try. | |
if (tryAgain) { | |
this.focusAndShowKeyboard(false) | |
} | |
} | |
} | |
} | |
} | |
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