Skip to content

Instantly share code, notes, and snippets.

@bmc08gt
Created September 14, 2021 02:55
Show Gist options
  • Save bmc08gt/67bf4cc4f47033fe47fd4586354756f2 to your computer and use it in GitHub Desktop.
Save bmc08gt/67bf4cc4f47033fe47fd4586354756f2 to your computer and use it in GitHub Desktop.
WindowInsets IME extensions
val View.windowInsetsCompat: WindowInsetsCompat?
get() {
val rootInsets = rootWindowInsets ?: return null
return WindowInsetsCompat.toWindowInsetsCompat(rootInsets)
}
val View.isKeyboardVisible: Boolean
get() = windowInsetsCompat?.isVisible(WindowInsetsCompat.Type.ime()) ?: false
fun View.hideKeyboard() {
ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())
}
fun View.showKeyboard() {
ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
}
fun View.doOnImeVisibilityChanged(
onShown: () -> Unit = {},
onDismissed: () -> Unit = {}
) {
doOnLayout {
// get init state of keyboard
var keyboardVisible = isKeyboardVisible
// whenever the layout resizes/changes, callback with the state of the keyboard.
viewTreeObserver.addOnGlobalLayoutListener {
val keyboardUpdateCheck = isKeyboardVisible
// since the observer is hit quite often, only callback when there is a change.
if (keyboardUpdateCheck != keyboardVisible) {
if (keyboardUpdateCheck) {
onShown()
} else {
onDismissed()
}
keyboardVisible = keyboardUpdateCheck
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment