What's the easiest way to animate between alignmen...
# compose
j
What's the easiest way to animate between alignments? Say,
Alignment.TopStart
->
Alignment.BottomStart
within a
Box
? Possibly-related: can ConstraintLayout animate between constraints (via movement not just crossfade or something)?
b
I actually just did something like this
If you checkout the BiasAlignment class, you’ll see that for the most part it’s just a pair of float values that describe where it’s at on the screen
So you can do something like this:
Copy code
BiasAlignment(
    -1f,
    placeholderAlignment
)
Copy code
val placeholderAlignment by animateFloatAsState(targetValue = if (isFocused || text.isNotEmpty()) -1f else 0f)
j
Oooh nice. Thanks!
b
No problem 🙂
There is probably a better way to do it, but honestly this worked really well for me so I just stuck with it
j
Haha based on your blurb you are solving a very similar problem as I am 😄
😂 1
a
the only thing I might change about this is to avoid recomposition as it animates by having an Alignment implementation that reads and returns the animated value when requested, so that only the layout invalidates during the animation. Otherwise, 👍
d
I'd recommend checking out this thread with animations using the new
onPlaced
modifier: https://twitter.com/TashaRamesh/status/1461289694616907777
You should be able to use the
animatePlacement
in the sample code here (https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/package-summary#(androidx.compose.ui.Modifier).onPlaced(kotlin.Function1) ) to animate movement for when constraints change in a ConstraintLayout. Alternatively, ConstraintLayout has an API for animating between constraints: https://github.com/androidx/constraintlayout/blob/main/constraintlayout/compose/sr[…]main/java/androidx/constraintlayout/compose/ConstraintLayout.kt
j
@Doris Liu Nice! I'll check that out, thank you! @Adam Powell would you mind elaborating a bit? I'm still wrapping my head around what causes recomposition. Do you mean something like
remember { SomeCustomAnimatedAlignment(...) }
?
a
Yes, though you don't necessarily need the remember either depending on how often the function would otherwise recompose. The idea being that the values returned by the Alignment change over the animation, not the Alignment object itself
👍 1
p
Is it possible in compose to animate say from center of screen to a certain (x, y) coordinate yet?
d
@Pulak
onPlaced
is designed to make that change (from center of screen to somewhere else) animatable. Check out the sample code
animatePlacement
linked above. If you add
animatePlacement
modifier to your element that you intend to move, you can expect the position change to be animated. We do plan on having official support for the
animatePlacement
concept in the near future. But because of
onPlaced
being experimental, we can't build animation APIs on top of it just yet.
👍 1