I want to slide out vertically from my initial position to another point very slowly. Suppose my initial position is 50.dp
THEN it goes to 49.dp
,48.dp
....0.dp
. I tried some piece of code but to goes to directly 0.dp and then hide which i don't want. Can you guys help me on this.
@OptIn(ExperimentalAnimationApi::class)
@Preview(showBackground = true)
@Composable
fun MoveText() {
var visible by remember { mutableStateOf(true) }
var yPosition by remember {
mutableStateOf(50.dp)
}
LaunchedEffect(key1 = visible) {
yPosition = if (visible) {
50.dp
} else {
0.dp
}
}
ScrollComposeTheme {
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = 16.dp, top = 16.dp)
) {
AnimatedVisibility(
visible = visible,
modifier = Modifier.padding(top = yPosition),
exit = slideOutVertically(
animationSpec = tween(4000),
)
) {
val color by transition.animateColor(label = "color") { state ->
if (state == EnterExitState.Visible) Color.Black else Color.Gray
}
Column {
Icon(
imageVector = Icons.Default.ShoppingCart,
tint = color,
contentDescription = null,
)
Text(
text = "Hello, Anna",
fontSize = 20.sp,
color = color,
)
}
}
Button(
modifier = Modifier
.absoluteOffset(y = 10.dp),
onClick = {
visible = !visible
},
) {
Text(text = "Move Text")
}
}
}
}
After research I got to use animateDpAsState
and which is fixed my problem. I am adding a code in here
@Preview(showBackground = true)
@Composable
fun MoveText() {
var visible by remember { mutableStateOf(true) }
val iconOffsetAnimation: Dp by animateDpAsState(
if (visible) 13.dp else 0.dp,
tween(1000)
)
val textOffsetAnimation: Dp by animateDpAsState(
if (visible) 19.dp else 5.dp,
tween(1000)
)
ScrollComposeTheme {
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = 16.dp, top = 16.dp)
) {
Column {
Icon(
modifier = Modifier
.absoluteOffset(y = iconOffsetAnimation),
imageVector = Icons.Default.ShoppingCart,
tint = Color.Black,
contentDescription = null,
)
Text(
modifier = Modifier
.absoluteOffset(y = textOffsetAnimation),
text = "Hello, Anna",
fontSize = 20.sp,
color = Color.Black,
)
}
Button(
modifier = Modifier
.absoluteOffset(y = 30.dp),
onClick = {
visible = !visible
},
) {
Text(text = "Move Text")
}
}
}
}