📌  相关文章
📜  Android Jetpack Compose 中的 Lottie 动画

📅  最后修改于: 2022-05-13 01:55:20.528000             🧑  作者: Mango

Android Jetpack Compose 中的 Lottie 动画

Lottie 是一个很棒的库,可以将动画文件添加到您的应用程序中。两天前 Jetpack compose 变得稳定,而且 Lottie 也支持 Compose。在本文中,我们将了解如何在 compose 应用中添加 Lottie 动画。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,显示带有暂停/播放和增加/减少速度按钮的 Lottie 动画。下面给出了一个示例 GIF,以了解我们将在本文中做什么

先决条件:

  • 安卓方面的知识。
  • 对 Jetpack 组合有很好的了解。

分步实施

第 1 步:创建一个新项目(或在现有 Compose 项目中使用它)



  • 打开 Android Studio(必须是最新版本(>=2020.3.1)。
  • 单击“新建项目”>“空撰写活动”。
  • 然后根据您的选择写入应用程序名称和包名称,然后单击完成。等待 Gradle 构建完成。

第 2 步:添加依赖项

打开构建d.gradle(app) 并添加以下依赖项。

第 3 步:下载 Lottie 文件并将其放入项目中

右键点击res > new > Android 资源目录。

输入raw来创建一个 raw 文件夹



现在前往 Lottie 下载您最喜欢的动画或使用本文中的动画(从此处下载)。下载后将其拖放到原始文件夹中。

第 4 步:使用 Lottie 动画

创建一个可组合的函数LottieExample()。

Kotlin
@Composable
fun LottieExample() {
  // codes to be added here
}


Kotlin
// to keep track if the animation is playing
// and play pause accordingly
var isPlaying by remember {
     mutableStateOf(true)
 }
  
// for speed
var speed by remember {
     mutableStateOf(1f)
 }


Kotlin
// remember lottie composition, which
// accepts the lottie composition result
val composition by rememberLottieComposition(
  
        LottieCompositionSpec
              // here `code` is the file name of lottie file
              // use it accordingly
            .RawRes(R.raw.code)
    )
  
    // to control the animation
    val progress by animateLottieCompositionAsState(
        // pass the composition created above
        composition,
  
        // Iterates Forever
        iterations = LottieConstants.IterateForever,
  
        // pass isPlaying we created above,
        // changing isPlaying will recompose
        // Lottie and pause/play
        isPlaying = isPlaying,
        
        // pass speed we created above,
        // changing speed will increase Lottie
        speed = speed,
  
        // this makes animation to restart
        // when paused and play
        // pass false to continue the animation 
        // at which is was paused
        restartOnPlay = false
  
)


Kotlin
// Column Composable
Column(
        Modifier
            .background(Color.White)
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
  
        // Heading
        Text(
            text = "Lottie",
            color = Color.Gray,
            fontSize = 70.sp,
            fontWeight = FontWeight.SemiBold,
            fontStyle = FontStyle.Italic,
            modifier = Modifier.padding(10.dp)
        )
  
  
        // LottieAnimation
        // Pass the composition
        // and the progress state
        LottieAnimation(
            composition,
            progress,
            modifier = Modifier.size(400.dp)
        )
  
        // Buttons to control the animation
        Row(
            horizontalArrangement = Arrangement.SpaceAround,
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
  
                // Button to decrease speed
                Button(
                    onClick = {
                        // check to prevent speed going negative
                        speed = max(speed - 0.25f, 0f)
                    },
                    // Button background color
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "-",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
  
                        )
                }
  
                // Button to Increase speed
                Text(
                    text = "Speed ( $speed ) ",
                    color = Color.Black,
                    fontWeight = FontWeight.Bold,
                    fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp)
  
                )
                Button(
                    onClick = {
                        // Increase the speed by 0.25
                        speed += 0.25f
                    },
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "+",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp
                    )
                }
            }
  
  
            // Button to pause and play
            Button(
                onClick = {
                    // change isPlaying state to pause/play
                    isPlaying = !isPlaying
                },
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = Color(0xFF0F9D58)
                )
            ) {
                Text(
                    // display text according to state
                    text = if (isPlaying) "Pause" else "Play",
                    color = Color.White
                )
            }
        }
    }


Kotlin
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
          LottieExample()
        }
    }
}


Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import kotlin.math.max
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
                LottieExample()
        }
    }
}
  
@Composable
fun LottieExample() {
  
    // to keep track if the animation is playing
    // and play pause accordingly
    var isPlaying by remember {
        mutableStateOf(true)
    }
    // for speed
    var speed by remember {
        mutableStateOf(1f)
    }
  
    // remember lottie composition ,which
    // accepts the lottie composition result
    val composition by rememberLottieComposition(
        LottieCompositionSpec
            .RawRes(R.raw.code)
    )
  
  
    // to control the animation
    val progress by animateLottieCompositionAsState(
        // pass the composition created above
        composition,
  
        // Iterates Forever
        iterations = LottieConstants.IterateForever,
  
        // pass isPlaying we created above,
        // changing isPlaying will recompose 
        // Lottie and pause/play
        isPlaying = isPlaying,
        
        // pass speed we created above,
        // changing speed will increase Lottie
        speed = speed,
  
        // this makes animation to restart when paused and play
        // pass false to continue the animation at which is was paused
        restartOnPlay = false
  
    )
  
    // Column Composable
    Column(
        Modifier
            .background(Color.White)
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // Heading
        Text(
            text = "Lottie",
            color = Color.Gray,
            fontSize = 70.sp,
            fontWeight = FontWeight.SemiBold,
            fontStyle = FontStyle.Italic,
            modifier = Modifier.padding(10.dp)
        )
  
        // LottieAnimation
        // Pass the composition and the progress state
        LottieAnimation(
            composition,
            progress,
            modifier = Modifier.size(400.dp)
        )
  
        // Buttons to control the animation
        Row(
            horizontalArrangement = Arrangement.SpaceAround,
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
  
                // Button to decrease speed
                Button(
                    onClick = {
                        // check to prevent speed going negative
                        speed = max(speed - 0.25f, 0f)
                    },
                    // Button background color
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "-",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
  
                        )
                }
  
                // Button to Increase speed
                Text(
                    text = "Speed ( $speed ) ",
                    color = Color.Black,
                    fontWeight = FontWeight.Bold,
                    fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp)
  
                )
                Button(
                    onClick = {
                        // Increase the speed by 0.25
                        speed += 0.25f
                    },
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "+",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp
                    )
                }
            }
  
            // Button to pause and play
            Button(
                onClick = {
                    // change isPlaying state to pause/play
                    isPlaying = !isPlaying
                },
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = Color(0xFF0F9D58)
                )
            ) {
                Text(
                    // display text according to state
                    text = if (isPlaying) "Pause" else "Play",
                    color = Color.White
                )
            }
        }
    }
}


我们需要创建 Lottie 的组合和进度状态。在同一个可组合中添加以下代码,解释请参考注释。

创建一个状态来保持速度和播放/暂停状态。在函数添加以下代码

科特林

// to keep track if the animation is playing
// and play pause accordingly
var isPlaying by remember {
     mutableStateOf(true)
 }
  
// for speed
var speed by remember {
     mutableStateOf(1f)
 }

科特林

// remember lottie composition, which
// accepts the lottie composition result
val composition by rememberLottieComposition(
  
        LottieCompositionSpec
              // here `code` is the file name of lottie file
              // use it accordingly
            .RawRes(R.raw.code)
    )
  
    // to control the animation
    val progress by animateLottieCompositionAsState(
        // pass the composition created above
        composition,
  
        // Iterates Forever
        iterations = LottieConstants.IterateForever,
  
        // pass isPlaying we created above,
        // changing isPlaying will recompose
        // Lottie and pause/play
        isPlaying = isPlaying,
        
        // pass speed we created above,
        // changing speed will increase Lottie
        speed = speed,
  
        // this makes animation to restart
        // when paused and play
        // pass false to continue the animation 
        // at which is was paused
        restartOnPlay = false
  
)

现在我们需要创建按钮并放置 Lottie 可组合。在同一个可组合函数添加以下代码。这些是基本的列、行、按钮和可组合的文本。有关更多信息,请参阅此内容。



科特林

// Column Composable
Column(
        Modifier
            .background(Color.White)
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
  
        // Heading
        Text(
            text = "Lottie",
            color = Color.Gray,
            fontSize = 70.sp,
            fontWeight = FontWeight.SemiBold,
            fontStyle = FontStyle.Italic,
            modifier = Modifier.padding(10.dp)
        )
  
  
        // LottieAnimation
        // Pass the composition
        // and the progress state
        LottieAnimation(
            composition,
            progress,
            modifier = Modifier.size(400.dp)
        )
  
        // Buttons to control the animation
        Row(
            horizontalArrangement = Arrangement.SpaceAround,
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
  
                // Button to decrease speed
                Button(
                    onClick = {
                        // check to prevent speed going negative
                        speed = max(speed - 0.25f, 0f)
                    },
                    // Button background color
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "-",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
  
                        )
                }
  
                // Button to Increase speed
                Text(
                    text = "Speed ( $speed ) ",
                    color = Color.Black,
                    fontWeight = FontWeight.Bold,
                    fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp)
  
                )
                Button(
                    onClick = {
                        // Increase the speed by 0.25
                        speed += 0.25f
                    },
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "+",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp
                    )
                }
            }
  
  
            // Button to pause and play
            Button(
                onClick = {
                    // change isPlaying state to pause/play
                    isPlaying = !isPlaying
                },
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = Color(0xFF0F9D58)
                )
            ) {
                Text(
                    // display text according to state
                    text = if (isPlaying) "Pause" else "Play",
                    color = Color.White
                )
            }
        }
    }

最后,从MainActivity类的 setcontent 调用这个可组合的。

科特林

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
          LottieExample()
        }
    }
}

下面是MainActivity.kt文件完整代码

科特林

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import kotlin.math.max
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
                LottieExample()
        }
    }
}
  
@Composable
fun LottieExample() {
  
    // to keep track if the animation is playing
    // and play pause accordingly
    var isPlaying by remember {
        mutableStateOf(true)
    }
    // for speed
    var speed by remember {
        mutableStateOf(1f)
    }
  
    // remember lottie composition ,which
    // accepts the lottie composition result
    val composition by rememberLottieComposition(
        LottieCompositionSpec
            .RawRes(R.raw.code)
    )
  
  
    // to control the animation
    val progress by animateLottieCompositionAsState(
        // pass the composition created above
        composition,
  
        // Iterates Forever
        iterations = LottieConstants.IterateForever,
  
        // pass isPlaying we created above,
        // changing isPlaying will recompose 
        // Lottie and pause/play
        isPlaying = isPlaying,
        
        // pass speed we created above,
        // changing speed will increase Lottie
        speed = speed,
  
        // this makes animation to restart when paused and play
        // pass false to continue the animation at which is was paused
        restartOnPlay = false
  
    )
  
    // Column Composable
    Column(
        Modifier
            .background(Color.White)
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // Heading
        Text(
            text = "Lottie",
            color = Color.Gray,
            fontSize = 70.sp,
            fontWeight = FontWeight.SemiBold,
            fontStyle = FontStyle.Italic,
            modifier = Modifier.padding(10.dp)
        )
  
        // LottieAnimation
        // Pass the composition and the progress state
        LottieAnimation(
            composition,
            progress,
            modifier = Modifier.size(400.dp)
        )
  
        // Buttons to control the animation
        Row(
            horizontalArrangement = Arrangement.SpaceAround,
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
  
                // Button to decrease speed
                Button(
                    onClick = {
                        // check to prevent speed going negative
                        speed = max(speed - 0.25f, 0f)
                    },
                    // Button background color
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "-",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
  
                        )
                }
  
                // Button to Increase speed
                Text(
                    text = "Speed ( $speed ) ",
                    color = Color.Black,
                    fontWeight = FontWeight.Bold,
                    fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp)
  
                )
                Button(
                    onClick = {
                        // Increase the speed by 0.25
                        speed += 0.25f
                    },
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0F9D58)
                    )
                ) {
                    Text(
                        text = "+",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp
                    )
                }
            }
  
            // Button to pause and play
            Button(
                onClick = {
                    // change isPlaying state to pause/play
                    isPlaying = !isPlaying
                },
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = Color(0xFF0F9D58)
                )
            ) {
                Text(
                    // display text according to state
                    text = if (isPlaying) "Pause" else "Play",
                    color = Color.White
                )
            }
        }
    }
}

运行应用程序并查看屏幕上的动画。

输出:

如果有任何问题,请参阅项目。

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!