Skip to content

Instantly share code, notes, and snippets.

@67Samuel
Last active August 2, 2023 07:41
Show Gist options
  • Save 67Samuel/160b3a03ea6fc71718e14dacf8fafbe1 to your computer and use it in GitHub Desktop.
Save 67Samuel/160b3a03ea6fc71718e14dacf8fafbe1 to your computer and use it in GitHub Desktop.
Detect Soft Keyboard
fun Activity.handleKeyboardVisibility(isInitialKeyboardVisible: Boolean = true, onOpen: () -> Unit, onClose: () -> Unit) {
var isKeyboardVisible = isInitialKeyboardVisible
val listener = OnGlobalLayoutListener {
window.decorView.apply {
val r = Rect()
getWindowVisibleDisplayFrame(r)
val isKeyboardCurrentlyVisible = height - r.bottom > height * 0.1399
if (!isKeyboardVisible && isKeyboardCurrentlyVisible) {
// Keyboard is open
isKeyboardVisible = true
onOpen()
} else if (isKeyboardVisible && !isKeyboardCurrentlyVisible) {
// Keyboard is closed
isKeyboardVisible = false
onClose()
}
}
}
(this as LifecycleOwner).lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
this@handleKeyboardVisibility.window.decorView.viewTreeObserver.addOnGlobalLayoutListener(listener)
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
this@handleKeyboardVisibility.window.decorView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment