Why does following code not animate box width? :th...
# compose
p
Why does following code not animate box width? 🤔
Copy code
@Composable
@Preview
private fun TestPreview() {
    var isShown by remember { mutableStateOf(true) }
    LaunchedEffect(Unit) {
        while (true) {
            delay(1000)
            isShown = !isShown
        }
    }

    Row(Modifier.animateContentSize()) {
        if (isShown) {
            Box(modifier = Modifier.background(Color.Red)
                .height(200.dp)
                .animateContentSize()
                .weight(1f)
            )
        }
        Box(modifier = Modifier.background(Color.Blue)
            .height(200.dp)
            .animateContentSize()
            .weight(1f)
        )
    }
}
s
The Row does not animate since it always just takes up the entire width. The blue box might be animating actually behind the red box. Try makig the red box transparent to see if that's the case. The Red box does not animate since it just exists as 200.dp or it does not exist at all. If you instead replaced the simple
weight(1f)
with a
if (isShown) Modifier.weight(1f) else Modifier.width(0.dp)
and removed the outer if statement so it is also in composition it might also animate
p
Now it animates half-way. I guess it doesn't like to animate when using
weight()
?
Copy code
Row(Modifier.animateContentSize()) {
    Box(
        modifier = Modifier.background(Color.Red)
            .height(200.dp)
            .animateContentSize()
            .let {
                if (isShown) {
                    it.weight(1f)
                } else {
                    it.width(0.dp)
                }
            }
    )
    Box(
        modifier = Modifier
            .background(Color.Blue)
            .height(200.dp)
            .animateContentSize()
            .weight(1f)
    )
}
s
Can you also play with putting animateContentSize modifier after the weight modifier? Just as an idea. Also remove the animateContentSize on the row itself, since it's not doing anything, also just in case.
p
I tried changing
animateContentSize()
in every possible way, doesn't help
The only way I managed to make transition work, is by calculating width of each item based on available width (screen width) and not using
weight()
, only
width()
s
Try without the weight, but a fixed width. If that works perfectly well, it may have something to do with weight indeed
Ah you tried that too, interesting indeed
p
only that works yeah, but I guess not ideal, that's why I'm wondering if I'm doing smth stupid 😄
s
If you try to apply the weight to an outside parent but then have an internal composable which does the animation, does that do anything?
Copy code
Box(
 modifier = Modifier.weight(1f)
) {
  Box(
   Modifier
   .background(Color.Blue)
   .matchParentSize()
   .animateContentSize()
 )
}
Or is it synced with the parent anyway due to matchParentSize()?
p
Doesn't seem to work. Whenever I put weight, it will instantly change Box size