How to create a composable that sizes to fit using Kotlin

Oscar de la Hera Gomez
Four flowers that represent Kotlin, Android, Jetpack Compose and Android Studio side by side. Beneath them sits the text “Dynamically Size Composable to Content.”

A step by step guide on creating a Jetpack Compose Composable that dynamically adapts its width & height to fit its content via a ConstraintLayout using Kotlin.

The following tutorial builds on our Open Source Kotlin project which can be downloaded using the link below, and aims to walk you through how to create a Composable that dynamically adapts to fit its content.

The composable that we create is very similar to the tooltip that we use in Price After.

We recommend that you checkout the main branch and carry out the steps described below. The changes that took place can be found on the tutorial/jetpack-compose/size-to-fit

git clone git@github.com:delasign/kotlin-android-starter-project.git

Step One: Add the Content

A screenshot of Android Studio showing the language jsons that were created as part of our localization tutorial. The link to this is found below.

Follow the tutorials below to add the relevant localizable strings, symbols or images to your Android project.

Step Two: Create the Composable

A screenshot of Android Studio showing the composable that dynamically adapts to fit its content. The code can be found below.

In the project, create a Composable that uses a ConstraintLayout.

This is the file that intends to use auto-layout to dynamically adapt to its content.

For this to work as desired, the elements within the Composable must touch the top, absoluteLeft, absoluteRight and bottom of the parent.

Please consult the code below if you wish to see how we created the composable. The LabelText was created as part of our Styleguide tutorial.

Step Three: Place the Composable

A screenshot of Android Studio showing you how we placed the composable within the UI of the app.

Add the composable to the app.

Step Four: Test

A picture showing the emulators visual in landscape and portrait.

Run the code and you will see that the composable adapts to fit the content based on the constraints.

In the example above, it has a different height (which is calculated dynamically) in landscape and portrait as the width is different on those two views.

If you wish to learn how to maintain states when the app changes orientation (i.e. goes from portrait to landscape or vice versa) follow the tutorial linked below.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details