Reputation: 21
I’m working on an animation in Jetpack Compose, where I want to display numbers with a fade-in and fade-out effect. Each number should fade out, then the new number should fade in, and this process should repeat. However, I am facing a strange issue:
Problem: The fade-in animation does not happen if I don’t put a small delay (delay(100)). If I omit the delay(100), the number flickers when it appears (appearing suddenly without the fade-in). I have already set a fadeIn duration in the tween(), but without this small delay, the fade-in does not occur.
Expected Behavior: The previous number fades out (with a specified fadeOut duration). The new number fades in (with a specified fadeIn duration). Each cycle happens without flickering.
How to Reproduce it: Just uncomment and comment the line of delay(100)
Here’s the code I’m using:
internal class MainActivity : AppCompatActivity() {
private val state by lazy { mutableIntStateOf(1) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BannerWithAnimation(state.intValue)
}
lifecycleScope.launch {
delay(2000)
state.intValue = 20
}
lifecycleScope.launch {
delay(40000)
state.intValue = 55
}
}
}
@Composable
fun BannerWithAnimation(num: Int) {
var currentNum by remember { mutableIntStateOf(num) }
var isVisible by remember { mutableStateOf(true) }
LaunchedEffect(num) {
if (num != 1) {
// Fade out the previous number
isVisible = false
delay(7000) // Wait for the previous number's fade-out duration
delay(100) // This small delay is necessary to prevent flickering and trigger fade-in
currentNum = num
// Fade in the new number
isVisible = true
}
}
AnimatedVisibility(
visible = isVisible,
enter = fadeIn(animationSpec = tween(15000)),
exit = fadeOut(animationSpec = tween(7000))
) {
Text(text = "$currentNum", color = Color.Cyan, fontSize = 220.sp)
}
}
Upvotes: 2
Views: 43