How to Handle Automatic Content Resizing when keyboard is visible in Jetpack Compose
As Android developers, we have all encountered the problem of the keyboard overlapping the content of our app, which can be frustrating for users.
In this article, we will explore how to implement automatic content resizing when the keyboard is visible in Jetpack Compose. Before, we start let’s see what are we talking about:
In the past we would have solved this problem by adding next line to AndroidManifest.xml
file:
android:windowSoftInputMode="adjustResize"
However, in a Compose-only app, this solution doesn’t work, so we need to find an alternative solution.
We came up with a reusable component that uses the .imePadding
modifier to automatically add padding whenever a keyboard is opened:
This simple component takes in content and ensures that it resizes automatically when the keyboard is opened. The usage of this component is straightforward and can be seen below:
KeyboardAware {
SearchSongScreen(...)
}
And the result is:
However, we soon realized that if we needed to have multiple TextFields
on one screen, the content would overlap again.
We somehow need to make the content scrollable as well in this case. For this we are going to need a couple more things:
We need to add scrollState
that we pass to .verticalScroll
modifier to our screen.
We need to create coroutineScope
with rememberCoroutineScope
. This creates a composition-aware scope, that we can use to launch a coroutine outside a composable.
In the end we also need to get the height of our keyboard of course. This can be done with WindowInsets.ime.getBottom(LocalDensity.current)
.
To wire everything up and get a working example, we use LaunchedEffect
with keyboardHeight
as a key. This means that that the block we pass to our LaunchedEffect
will be (re)launched whenever the height of our keyboard changes. Exactly what we need!
Lastly we call scrollState.scrollBy(keyboardHeight.toFloat())
, which will scroll our content by the height of our keyboard. We need to use our coroutineScope
that we created earlier here, since scrollBy
is a suspend function.
The final solution looks like this:
And that’s it! 🥳 We have a final solution that should work with literally any screen. I hope you find this short tutorial useful. 👨💻
Full code available at: https://github.com/Kuglll/KeyboarAwareSample/tree/main