What's the preferred way to create the expand/coll...
# compose
c
What's the preferred way to create the expand/collapse effect on a row item? I think I saw Chris Banes do this on twitter once (months ago) but I can't find it. It looks like there are two ways to do this. 1. On the root composable you can call the
.animateContentSize()
modifier 2. Have the expandable content wrapped in
AnimatedVisibility {}
composable At runtime the behavior of
AnimatedVisibility
looks slightly better I think? Code examples of each in thread.
Copy code
@ExperimentalAnimationApi
@Composable
fun ExpandCollapse1(
) {
    var visible by remember { mutableStateOf(false) }
    Column(
        modifier = Modifier.clickable { visible = !visible }.padding(48.dp).animateContentSize()
    ) {
        Row() {
            Text("Testing with animatedVisibility")
        }
        if (visible) {
            Column {
                Text(
                    "Testing second line",
                    modifier = Modifier.padding(bottom = 24.dp),
                )
            }
        }
    }
}

@ExperimentalAnimationApi
@Composable
fun ExpandCollapse2(
) {
    var visible by remember { mutableStateOf(false) }
    Column(modifier = Modifier.clickable { visible = !visible }.padding(48.dp)) {
        Row() {
            Text("Testing with animatedVisibility")
        }
        AnimatedVisibility(visible = visible) {
            Column {
                Text(
                    "Testing second line",
                    modifier = Modifier.padding(bottom = 24.dp),
                )
            }
        }
    }
}
t
In AnimatedVisibility you can set the enter and exit animation.
Copy code
AnimatedVisibility(                  
                    visible = visible,
                    enter = expandHorizontally(),
                    exit = shrinkHorizontally()
                )
maybe you want expandVertically()
d
They are both perfectly valid options for this use case. It's a matter of how much control you'd like to have over the appearing/disappearing content.
animateContentSize
is the minimum effort approach that instantly adds/removes content and animates the container to smooth over the size impact to the parent.
AnimatedVisibiity
gives you more control on how the new content appear/disappear with a few more lines. In some cases the appearing/disappearing content has siblings whose positions are dependent on the size of it. For example, if you have more items below the
if(visible)
content in your snippet, I'd recommend using
AnimatedVisibility
over
animateContentSize
on parent, so that those siblings won't jump to the new position. 🙂
c
Great explanation. Thank you!
👍 1