- Increase Decrease in jetpack compose
@Composable
fun CounterQty(mainViewModel: MainViewModel = viewModel()) {
var seconds by remember { mutableIntStateOf(0) } // Replace with your ViewModel if required
var previousSeconds by remember { mutableIntStateOf(0) } // To track the previous value for animation direction
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
AnimatedContent(
targetState = seconds,
transitionSpec = {
// Check if the target value is greater or less than the current value
if (targetState > previousSeconds) {
addAnimationForIncrease() // Animation for increment
} else {
addAnimationForDecrease() // Animation for decrement
}.using(
sizeTransform = SizeTransform(clip = false)
)
}, label = ""
) { targetCount ->
Text(
text = "$targetCount",
style = TextStyle(fontSize = MaterialTheme.typography.h1.fontSize),
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(16.dp))
// Buttons for increment and decrement
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = {
if (seconds > 0) {
previousSeconds = seconds // Store current value before decrement
seconds--
}
}, // Decrease seconds
modifier = Modifier.padding(8.dp)
) {
Icon(
imageVector = Icons.Default.Send,
contentDescription = "Decrease",
tint = MaterialTheme.colors.primary
)
}
IconButton(
onClick = {
previousSeconds = seconds // Store current value before increment
seconds++
}, // Increase seconds
modifier = Modifier.padding(8.dp)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Increase",
tint = MaterialTheme.colors.primary
)
}
}
}
}
fun addAnimationForIncrease(duration: Int = 800): ContentTransform {
return (slideInVertically(animationSpec = tween(durationMillis = duration)) { height -> height } + fadeIn(
animationSpec = tween(durationMillis = duration)
)).togetherWith(slideOutVertically(animationSpec = tween(durationMillis = duration)) { height -> -height } + fadeOut(
animationSpec = tween(durationMillis = duration)
))
}
fun addAnimationForDecrease(duration: Int = 800): ContentTransform {
return (slideInVertically(animationSpec = tween(durationMillis = duration)) { height -> -height } + fadeIn(
animationSpec = tween(durationMillis = duration)
)).togetherWith(slideOutVertically(animationSpec = tween(durationMillis = duration)) { height -> height } + fadeOut(
animationSpec = tween(durationMillis = duration)
))
}
0 Comments