androidandroid-jetpack-composeandroid-buttonandroid-compose-buttonandroid-jetpack-compose-button

How to animate width of a button in Jetpack Compose


Let's say I have a Composable like this :

@Composable
fun LoadingButton() {
    val (isLoading, setIsLoading) = state { false }

    Button(
        onClick = setIsLoading,
        text = {
            if (isLoading) {
                Text(text = "Short text")
            } else {
                Text(text = "Very very very long text")
            }
        }
    )
}

How can I animate the width update of my button ?

I'm well aware that I could add a preferredWidth modifier to the button and animate this width with :

val buttonWidth = animate(target = if (isLoading) LoadingButtonMinWidth else LoadingButtonMaxWidth)

But this is not my what I want. I need to animate the automatic "wrap-content" width.

Thanks in advance.


Solution

  • You need to add an animateContentSize modifier to the Text Composable:

    @Composable
    fun LoadingButton() {
        val (isLoading, setIsLoading) = state { false }
        Button(onClick = { setIsLoading(!isLoading) }) {
            Text(
                text = if (isLoading) {
                   "Short text"
                } else {
                    "Very very very long text"
                },
                modifier = Modifier.animateContentSize()
            )
        }
    }