Last active
August 2, 2023 07:41
-
-
Save 67Samuel/160b3a03ea6fc71718e14dacf8fafbe1 to your computer and use it in GitHub Desktop.
Detect Soft Keyboard
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
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