I am experimenting with animated buttons using GIF files and I encountered a strange error that I can’t seem to fix without messing up something else.
Let me explain. I have these 4 buttons (2 static loops and 2 transition animations). Initially, everything runs smoothly except for one thing. After 4 interactions with the on/off button, the fifth time you can see what I think is the last frame of the due transition animation flicker very briefly. It doesn’t happen at all the first 4 times. These gif images were preloaded on my onCreate function. (I will post relevant fragments of my code)
private lateinit var offButton: ImageView
private lateinit var onButton: ImageView
private lateinit var offToOnButton: ImageView
private lateinit var onToOffButton: ImageView
private fun preloadGifs() {
Glide.with(this).asGif().load(R.drawable.off_to_on_button).preload()
Glide.with(this).asGif().load(R.drawable.on_to_off_button).preload()
Glide.with(this).asGif().load(R.drawable.on_button).preload()
Glide.with(this).asGif().load(R.drawable.off_button).preload()
}
I managed to find a way to fix this entirely by creating a resetState() function in order to clear the GIFs. It worked, but now everything becomes extremely slow after the first off to on to off cycle.
private fun resetState() {
// Remove all callbacks and messages to ensure no pending handlers interfere
Handler(Looper.getMainLooper()).removeCallbacksAndMessages(null)
// Clear the two problematic gifs.
Glide.with(this).clear(offToOnButton)
Glide.with(this).clear(onToOffButton)
}
Surely there is a different way to handle all this and I would like to know your insights. At least I would like to know more about this problems. Originally, why does it fail only after 4 interactions? I try calling preloadGifs() on my resetState function, but it obviously didn’t work. What can I do? Than you for reading my question.