Hi there, how do you detect soft keyboard visibili...
# compose
n
Hi there, how do you detect soft keyboard visibility changes? On stack overflow some solutions are using the global layout listener, but I really don't like this solution because this method is called many times. The only "good" solution I have found is to use WindowInsets in the onCreate method of my main activity:
Copy code
ViewCompat.setOnApplyWindowInsetsListener(window.decorView) { _, insets ->
    val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
    onSoftKeyboardVisibilityChange(isKeyboardVisible)// own method which notifies me of changes
    insets
}
This way worked in the emulator (Pixel 3a API 30) but not on my phone (Galaxy S8 API 28) On top of that after launching my app, I noticed that my statusBarColor and navigationBarColor from themes.xml no longer work (status and nav bars are white or dark according to the theme instead of my own colors set in themes.xml) I tried to change
window.navigationBarColor
and
window.statusBarColor
in the setContent without success I don't understand what's going on. Is it possible to have an explanation ?
i
Have you considered using the
insets
module of Accompanist? It has support for keyboard insets https://google.github.io/accompanist/insets/
👍 1
n
I managed to make it work with accompanist, but I still don't understand why my first attempt does not work
c
@Nicolas Acart Would you mind sharing your solution that uses accompanist? I can check if the keyboard is visible using
LocalWindowInsets.current.ime.isVisible
, but I don't see a way to add a listener for when this visibility changes, without resorting to calling
ViewCompat.setOnApplyWindowInsetsListener(window.decorView)
in the Activity. Is this what you ended up doing? I'd like to not have to use the Activity at all and keep this isolated to the Compose tree if possible.
n
@Chuck Stein Sorry for the delay. I end up using :
Copy code
WindowCompat.setDecorFitsSystemWindows(window, false)
at the start of the onCreate method of my activity. And then :
Copy code
LocalWindowInsets.current.ime.isVisible
wherever I need it. By the way, I found that using
LocalWindows.current.ime.animationInProgress
could be very useful sometimes when you need to know that the keyboard is opening or closing instead of opened or closed.
Oh and if you need to launch some code dont forget that you can use
Copy code
LaunchedEffect(LocalWindows.current.ime.isVisible) {
    //TODO()
}
c
Thanks for the response. I ended up using
snapshotFlow
inside of a
LaunchedEffect
to react to visibility changes. I wonder if just using
LaunchedEffect
directly like that works the same way?