I have the following code:
if (isExtracting) {
extractionButton.cancelAnimation()
extractionButton.repeatCount = ValueAnimator.INFINITE
extractionButton?.let { extractionButton.setComposition(composition) }
extractionButton.playAnimation()
} else {
extractionButton.setImageResource(R.drawable.extraction_button_background)
}
When I run the animation first, everything works correctly. However, when the state changes and the image is set and afterwards the state changes again and the animation should restart, the animation won't load. And the image is shown instead.
Any idea how to run the animation again?
CodePudding user response:
This is how I did it. Making sure that isExtracting flag toggles after some time to mimic the state change.
XML:
<com.airbnb.lottie.LottieAnimationView
android:id="@ id/extractionButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_rawRes="@raw/camera"
app:lottie_autoPlay="false"/>
Activity:
class MainActivity : AppCompatActivity() {
private var isExtracting = true
private val extractionButton: LottieAnimationView by lazy { findViewById(R.id.extractionButton) }
private lateinit var composition: LottieComposition
private var job: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//change R.raw.camera with your lottie file
LottieCompositionFactory.fromRawRes(this,R.raw.camera).addListener {
it?.let {
composition = it
play()
}
}
}
private fun play() {
if (isExtracting) {
extractionButton.cancelAnimation()
extractionButton.repeatCount = ValueAnimator.INFINITE
extractionButton.setComposition(composition)
extractionButton.playAnimation()
toggleAfterDelay()
} else {
//change R.drawable.ic_android with your drawable
extractionButton.setImageResource(R.drawable.ic_android)
toggleAfterDelay()
}
}
private fun toggleAfterDelay() {
job?.cancel()
job = MainScope().launch {
delay(3000)
isExtracting = !isExtracting
play()
}
}
}
Try running this in an isolated environment(just a new project with Lottie) & see the result.
Output:
CodePudding user response:
Mayur was right. However, I put the image in a recycler view. So for this reason, I had also to follow this suggestion.
So I needed to add this method in my ViewHolder:
fun clearAnimation() {
binding.extractionButton.cancelAnimation()
val drawable: Drawable? = binding.extractionButton.drawable
if (drawable is LottieDrawable) {
drawable.clearComposition()
}
}
and this code to the RecyclerAdapter:
override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
super.onViewRecycled(holder)
if (holder is MyViewHolder) {
holder.clearAnimation()
}
}
However, since Mayur was right and his answer helped me a lot, I accepted his answer :-)
