Created
September 14, 2021 02:55
-
-
Save bmc08gt/67bf4cc4f47033fe47fd4586354756f2 to your computer and use it in GitHub Desktop.
WindowInsets IME extensions
This file contains hidden or 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
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