Android Lottie动画开源项目的使用

本文介绍了如何在Android项目中集成Lottie库,通过在build.gradle文件添加依赖,然后创建LottieAnimationUtils工具类来封装加载、播放、暂停和停止Lottie动画的功能。在布局文件中添加LottieAnimationView,并在Activity或Fragment中调用工具类方法来控制动画。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,请确保在项目的 build.gradle 文件中添加了 Lottie 的依赖项:

dependencies {
    implementation 'com.airbnb.android:lottie:3.7.2'
}

接下来,我们将创建一个名为 LottieAnimationUtils.java 的工具类来封装 Lottie 的基本功能:

import android.view.View;
​
import com.airbnb.lottie.LottieAnimationView;
​
public class LottieAnimationUtils {
​
    public static void loadAnimation(LottieAnimationView animationView, String fileName,
                                     boolean loop, boolean autoPlay) {
        animationView.setAnimation(fileName);
​
        if (loop) {
            animationView.setRepeatCount(LottieDrawable.INFINITE);
        } else {
            animationView.setRepeatCount(0);
        }
​
        if (autoPlay) {
            animationView.playAnimation();
        }
    }
​
    public static void play(LottieAnimationView animationView) {
        if (!animationView.isAnimating()) {
            animationView.playAnimation();
        }
    }
​
    public static void pause(LottieAnimationView animationView) {
        if (animationView.isAnimating()) {
            animationView.pauseAnimation();
        }
    }
​
    public static void stop(LottieAnimationView animationView) {
        animationView.cancelAnimation();
        animationView.setProgress(0);
    }
​
    public static void setVisibility(LottieAnimationView animationView, boolean visible) {
        animationView.setVisibility(visible ? View.VISIBLE : View.GONE);
    }
}

在布局文件中添加 LottieAnimationView:

<com.airbnb.lottie.LottieAnimationView
    android:id="@+id/animation_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:lottie_autoPlay="false"
    app:lottie_loop="false" />

在 Activity 或 Fragment 中使用这些封装方法:

private LottieAnimationView mAnimationView;
​
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
​
    mAnimationView = findViewById(R.id.animation_view);
​
    // 加载 Lottie 动画
    LottieAnimationUtils.loadAnimation(mAnimationView, "your_animation.json", true, true);
}
​
@Override
protected void onPause() {
    super.onPause();
    LottieAnimationUtils.pause(mAnimationView);
}
​
@Override
protected void onResume() {
    super.onResume();
    LottieAnimationUtils.play(mAnimationView);
}

以上代码展示了如何在 Activity 或 Fragment 中使用 LottieAnimationView 来播放 Lottie 动画。首先,我们创建了一个 LottieAnimationUtils 工具类来封装 Lottie 的基本功能。在布局文件中添加 LottieAnimationView,然后在 Activity 或 Fragment 中调用工具类的方法来加载、播放、暂停和停止动画。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值