How to Handle Automatic Content Resizing when keyboard is visible in Jetpack Compose

Mark Frelih
3 min readMar 2, 2023

--

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:

Keyboard overlaps the content example

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 .imePaddingmodifier 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:

Content resizes automatically when keyboard is opened example

However, we soon realized that if we needed to have multiple TextFieldson one screen, the content would overlap again.

Keyboard overlaps the content again example

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:

The final scrollable resizing content example

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

If you want to connect with me, feel free to do so on Github or LinkedIn.

--

--

Mark Frelih

Android Engineer @Infinum | Kotlin | Compose | KMM | Flutter