We just launched Compose Examples featuring over 150+ components! Check it out →

animateContentSize

Common

Modifier in Compose Animation

This modifier animates its own size when its child modifier (or the child composable if it is already at the tail of the chain) changes size. This allows the parent modifier to observe a smooth size change, resulting in an overall continuous visual change.

A [FiniteAnimationSpec] can be optionally specified for the size change animation. By default, [spring] will be used.

Last updated:

Installation

dependencies {
   implementation("androidx.compose.animation:animation:1.8.0-alpha01")
}

Overloads


fun Modifier.animateContentSize(
    animationSpec: FiniteAnimationSpec<IntSize> =
        spring(
            stiffness = Spring.StiffnessMediumLow,
            visibilityThreshold = IntSize.VisibilityThreshold
        ),
    finishedListener: ((initialValue: IntSize, targetValue: IntSize) -> Unit)? = null
): Modifier

Parameters

namedescription
animationSpeca finite animation that will be used to animate size change, [spring] by default
finishedListeneran optional listener to be called when the content change animation is completed.

fun Modifier.animateContentSize(
    animationSpec: FiniteAnimationSpec<IntSize> =
        spring(
            stiffness = Spring.StiffnessMediumLow,
            visibilityThreshold = IntSize.VisibilityThreshold
        ),
    alignment: Alignment = Alignment.TopStart,
    finishedListener: ((initialValue: IntSize, targetValue: IntSize) -> Unit)? = null,
): Modifier

Parameters

namedescription
animationSpeca finite animation that will be used to animate size change, [spring] by default
alignmentsets the alignment of the content during the animation. [Alignment.TopStart] by default.
finishedListeneran optional listener to be called when the content change animation is completed.

Code Example

AnimateContent

@Composable
fun AnimateContent() {
    val shortText = "Hi"
    val longText = "Very long text\nthat spans across\nmultiple lines"
    var short by remember { mutableStateOf(true) }
    Box(
        modifier =
            Modifier.background(Color.Blue, RoundedCornerShape(15.dp))
                .clickable { short = !short }
                .padding(20.dp)
                .wrapContentSize()
                .animateContentSize()
    ) {
        Text(
            if (short) {
                shortText
            } else {
                longText
            },
            style = LocalTextStyle.current.copy(color = Color.White)
        )
    }
}
by @alexstyl