We'll be looking at how to animate position changes using Dp in this series.
Let's define the card position as Enum's
//
enum class CardPosition {
IS_LEFT,
IS_RIGHT
}
We'll be using a BoxWithConstraints for this mainly it returns as the current size of the box where we could use the offset modifier to set the current position
BoxWithConstraints(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.border(width = 2.dp, shape = RoundedCornerShape(15), color = Blue)
.background(color = Color.Transparent, shape = RoundedCornerShape(15))
) {
// --> 1
var currentState by remember { mutableStateOf(CardPosition.IS_LEFT) }
// --> 2
val transition = updateTransition(currentState, label = "First Trans")
// --> 3
val color by transition.animateColor(transitionSpec = {
tween(800, easing = LinearOutSlowInEasing)
}, label = "") {
when (it) {
CardPosition.IS_RIGHT ->
Blue
else -> Green
}
}
// --> 4
val xOffset by transition.animateDp(
transitionSpec = {
tween(800, easing = LinearOutSlowInEasing)
}, label = "xOffset"
) { state ->
when (state) {
CardPosition.IS_LEFT -> 0.dp
CardPosition.IS_RIGHT -> this.maxWidth - 165.dp
}
}
Card(
elevation = 3.dp,
shape = RoundedCornerShape(100),
backgroundColor = color,
onClick = {
currentState = if (currentState == CardPosition.IS_LEFT) {
CardPosition.IS_RIGHT
} else {
CardPosition.IS_LEFT
}
}, indication = rememberRipple(),
modifier = Modifier
// --> 5
.offset(x = xOffset, 0.dp)
.padding(vertical = 15.dp, horizontal = 5.dp)
.width(150.dp)
) {
Text(
text = if (currentState == CardPosition.IS_LEFT) "Move To Right" else "Move To Left",
textAlign = TextAlign.Center,
color = White,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 5.dp)
)
}
}
- We set the current position of the Card.
Use the updateTransition.. animations api to hold the current position.
Learn more about updateTransitionSince we want to change the color on whether the card is at the right or left we declare a color variable update the current color accordingly
We need an xOffSet to determine and set the current position of the card.
Finally we set this using the offset modifier in Dp. (NB: This could also be done with IntOffSet{} for int values)
Top comments (0)