如何在安卓(Java)中设置Lottie动画的循环次数?

7

我在使用Lottie文件进行动画时遇到了问题。我无法在加载后设置循环次数,而是一直循环播放,但我想设置固定的循环次数。

活动XML

 <com.airbnb.lottie.LottieAnimationView
        android:layout_centerInParent="true"
        android:id="@+id/animation_view_1"
        android:layout_width="150dp"
        android:layout_height="150dp"
        app:lottie_autoPlay="true"
        app:lottie_loop="true" />

Java中的Activity

animationView.setVisibility(View.VISIBLE);
        animationView.setAnimation(fileName);
        animationView.loop(true);
        animationView.playAnimation();
4个回答

15

animationView.loop(true); 已经被弃用。 除了Phan Van Linh的回答之外,还可以使用 .xml 文件。

<com.airbnb.lottie.LottieAnimationView
        ...
        app:lottie_repeatCount="3"
        />

使用Java,您可以使用

animationView.setRepeatCount(LottieDrawable.INFINITE);// for Infinite loops

或者

animationView.setRepeatCount(3);// for 3 loops

以上的答案都很完美,但还有一种更简单的方法, 这已经被弃用了,但现在它仍然有效animationView.loop(true); - Tushar Pandey
1
是的,为了未来的目的,我们不应该使用animationView.loop(true); - Amin Pinjari

6

尝试

<com.airbnb.lottie.LottieAnimationView
        ...
        app:lottie_repeatCount="3"
        />

3
如果您使用Jetpack Compose:
  1. 从资源中获取Lottie合成:
// Get lottie composition
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.idea_anim))
  1. 为合成图创建动画状态,设置迭代次数使用iterations = 3,对于无限循环我们使用iterations = LottieConstants.IterateForever
// State of animation for composition
val progress by animateLottieCompositionAsState(
    composition = composition,
    iterations = LottieConstants.IterateForever
)
  1. 创建 LottieAnimation 组合项:
LottieAnimation(
    composition = composition,
    progress = { progress }
)

完整代码如下:
@Composable
fun AnyScreen() {
    // Get lottie composition
    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.idea_anim))

    // State of animation for composition
    val progress by animateLottieCompositionAsState(
        composition = composition,
        iterations = LottieConstants.IterateForever
    )

    LottieAnimation(
        composition = composition,
        progress = { progress }
    )
}

0

如果您想以编程方式实现,还可以使用方法setRepeatCount()

animationView.setRepeatCount(count)

/** * 设置动画应重复的次数。如果重复计数为0,则动画永远不会重复。如果重复计数大于0或{@link LottieDrawable#INFINITE},则将考虑重复模式。默认情况下,重复计数为0。 * * @param count 动画应重复的次数 */ public void setRepeatCount(int count) { lottieDrawable.setRepeatCount(count); }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接