Skip to content

Instantly share code, notes, and snippets.

@auyanik
Created January 27, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auyanik/3e82af6c3bdf6b92e39a9d2a7f89c62d to your computer and use it in GitHub Desktop.
Save auyanik/3e82af6c3bdf6b92e39a9d2a7f89c62d to your computer and use it in GitHub Desktop.
Keyboard open and close listener
private val open = KeyboardState.OPEN // change value true
private val close = KeyboardState.CLOSE // change value false
private var lastKeyboardState = close
fun listener(rootView: View?, keyboardState: (KeyboardState) -> Unit) {
rootView?.viewTreeObserver?.addOnGlobalLayoutListener {
val rect = Rect().apply { rootView.getWindowVisibleDisplayFrame(this) }
val screenHeight = rootView.height
val keypadHeight = screenHeight - rect.bottom
if (keypadHeight > screenHeight*0.15) {
if (lastKeyboardState == close) keyboardState.invoke(open)
lastKeyboardState = open
} else {
if (lastKeyboardState == open) keyboardState.invoke(close)
lastKeyboardState = close
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment