Skip to content

Instantly share code, notes, and snippets.

@Kashif-E
Created December 9, 2024 08:27
Show Gist options
  • Save Kashif-E/438a8c7928b11b286f39fc9675618ac3 to your computer and use it in GitHub Desktop.
Save Kashif-E/438a8c7928b11b286f39fc9675618ac3 to your computer and use it in GitHub Desktop.
This helps you listen to keyboard change like visibility and height change in compose
@Composable
fun KeyboardListener(
onKeyboardVisibilityChanged: (Boolean, Int) -> Unit
) {
val view = LocalView.current
val density = LocalDensity.current
DisposableEffect(view) {
ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets ->
val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
val keyboardHeightPx = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
val keyboardHeightDp = with(density) { keyboardHeightPx.toDp() }
// Notify about keyboard visibility and height
onKeyboardVisibilityChanged(imeVisible, keyboardHeightDp.value.dpToPx.roundToInt())
insets
}
onDispose { ViewCompat.setOnApplyWindowInsetsListener(view, null) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment