Android-Compose 切换Lottie-Compose动画资源

背景

Lottie动画现在已经是很多应用中必备的动画,而Jetpack-Compose也是谷歌推出的代码式编写UI的新框架,一旦它们遇到一起了,又会产生怎样的碰撞呢?又会产生怎样的火花呢?

compose项目引进 Lottie-compose

implementation 'com.airbnb.android:lottie-compose:4.2.2'

在布局中使用LottieAnimation

常用的是下面两个方法,这里就不多做介绍了,官方已经介绍得很仔细了。

  • LottieAnimation(LottieCompositionSpec, Modifier)
  • LottieAnimation(LottieCompositionSpec, Progress, Modifier)

正题开始,下面我们要介绍的是如何动态替换动画资源

LottieAnimatable 类,对的,使用该类能实现我们要的结果,配合使用LaunchedEffect即可动态替换动画资源。

下面展示一个伪代码案例:

    val anim0Composition = rememberLottieComposition(
        LottieCompositionSpec.RawRes(R.raw.lottie_anim0),
        "lottie/anim0"
    )
    val anim1Composition = rememberLottieComposition(
        LottieCompositionSpec.RawRes(R.raw.anim1),
        "lottie/anim1"
    )
    var selectIndex by remember { mutableStateOf(0) }
    var touched by remember { mutableStateOf(false) }
    val animation = rememberLottieAnimatable()
    LaunchedEffect(selectIndex) { //如果主题变更,就切换动画
        animation.animate(
            when (selectIndex) {
                1 -> anim1Composition
                else -> anim0Composition
            }.await()
        )
    }
    LottieAnimation(
            modifier = Modifier
                .fillMaxSize()
                .pointerInput(Unit) {
                    detectTapGestures {
                         selectedIndex =  if(selectedIndex  == 1) 0 else 1 
                    }
                },
            progress = animation.progress,
            composition = animation.composition
        )

具体使用起来怎么样,大家可以去试一试。第一次使用Jetpack-Compose Lottie 确实花了一些时间去处理,其中一个问题是如果raw的资源使用的都是一个文件,也要复制多份放入raw文件中并引入代码中,不然图片资源无法替换,无法生效。

希望以上代码对您有所启发。
以上内容均为原创,如需转载,请注明出处,感谢!

你可能感兴趣的:(Android-Compose 切换Lottie-Compose动画资源)