https://kotlinlang.org logo
#compose
Title
# compose
r

ribesg

10/27/2023, 2:19 PM
I'm a beginner with Compose UI and I'm playing with theming. I'm using material3. I've got a simple Scaffold with a TopAppBar and a LazyColumn list as content. I have a button that changes the theme. I noticed that the theme change is instantaneous everywhere but in the TopAppBar, where the background color change is animated. Is this normal default behavior? How do I either disable or generalize this to all material3 components? Half animating changes looks weird
o

Oleksandr Balan

10/27/2023, 4:13 PM
I think the
TopAppBar
would be the only one with this behavior, as it animates it's background based on the scrolling, see Behavior - Scrolling. So this piece of code in the
SingleRowTopAppBar
does this transition:
Copy code
// Obtain the container color from the TopAppBarColors using the `overlapFraction`. This
// ensures that the colors will adjust whether the app bar behavior is pinned or scrolled.
// This may potentially animate or interpolate a transition between the container-color and the
// container's scrolled-color according to the app bar's scroll state.
val colorTransitionFraction = scrollBehavior?.state?.overlappedFraction ?: 0f
val fraction = if (colorTransitionFraction > 0.01f) 1f else 0f
val appBarContainerColor by animateColorAsState(
    targetValue = colors.containerColor(fraction),
    animationSpec = spring(stiffness = Spring.StiffnessMediumLow)
)
If you do not want this animation to happen I guess you may try to wrap your
TopAppBar
in the
key
composable with a key of the current theme. Maybe you can even use surface color as key also. So something like that:
Copy code
key(MaterialTheme.colorScheme.surface) {
    TopAppBar(
        title = {  }
    )
}
In theory it could abort the transition and immediately take the new color from the theme. What is strange I do not see this animation code for
MediumTopAppBar
and
LargeTopAppBar
🤔 So maybe they behave differently 🤷
r

ribesg

10/27/2023, 4:17 PM
I guess this is one of the reasons it's still marked as experimental, but yeah, such difference in behavior of an important/basic composable is weird when you encounter it. I'm just playing with the very basics of a mobile app view (title and list of stuff) and I already need workarounds 😄 Thanks for the key trick, I'll try it.