---
title: "通过 Lottie 动画展示用户进度"
description: "在流程屏幕上以 Lottie 动画形式展示每个用户的进度，例如每日连续打卡记录。"
---

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/zh/llms.txt).

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

按照此方案，将用户进度以 Lottie 动画的形式展示——例如，用一个逐渐填充的圆环来表示用户的每日连续打卡天数。你的应用会在[自定义元素](flow-custom-elements)中以原生 Lottie 视图渲染该动画。

<DocVideo id="custom-element-lottie-demo.mp4" width="300px" alt="最终效果演示：用户点击「查看我的连续打卡」，进入下一屏后，圆环填充至 7 天中的第 4 天。" />

## 开始之前 \{#before-you-start\}

- 将您的应用更新至 Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 或更高版本。更早版本的 SDK 会为每个自定义元素显示[备用内容](flow-custom-elements#set-fallback-content)。
- 配置您的应用以[获取](kmp-get-pb-paywalls)和[展示](kmp-present-paywalls)流程。
- 参照 [Kotlin Multiplatform 指南](kmp-flow-custom-elements#before-you-start)，为自定义元素配置应用的原生代码。
- 在 iOS 上，通过 Swift Package Manager 将 Lottie 添加到 Xcode 中的应用 target，地址为 `https://github.com/airbnb/lottie-spm.git`。
- 在 Android 上，[配置您的 Android 项目](kmp-flow-custom-elements#set-up-your-android-project)，包括 Jetpack Compose。本示例中的动画视图是一个可组合项（composable）。如果您的应用未使用 Compose Multiplatform，请在 `androidMain` 依赖中添加 Compose Foundation，包名为 `androidx.compose.foundation:foundation`，无需指定版本号，版本由 `io.adapty:android-ui` 的 Compose BOM 统一管理。同时从 `com.airbnb.android:lottie-compose` 添加适用于 Jetpack Compose 的 Lottie。

准备一个 `.json` 格式的 Lottie 动画，或下载示例文件 [`streak_ring.json`](https://raw.githubusercontent.com/adaptyteam/adapty-docs/refs/heads/main/Downloads/streak_ring.json)。应用会从头播放动画，并按进度比例停止，例如进度为 50% 时停在中间位置。为了准确呈现进度，动画需要满足以下要求：

- 第一帧不显示任何进度，最后一帧显示完整进度。
- 匀速播放，不带缓动效果。如果动画开始时较慢、后来加速，则播放到一半时显示的进度会少于 50%。

## 1. 将自定义元素添加到屏幕 \{#1-add-the-custom-element-to-the-screen\}

在流程与付费墙编辑工具中，向流程屏幕[添加自定义元素](flow-custom-elements#add-and-configure)，并为动画进行如下配置：

- **类型**：`lottie_animation`。
- **ID**：`streak_ring`。在本示例中，ID 同时也是动画文件的名称。
- **高度**：保持默认的**固定**高度。动画会自动缩放以适应自定义元素的尺寸。

在自定义元素内部，添加一个包含圆环静态图片的[**图片**](custom-media#image)。当用户使用的应用版本不支持播放动画时，该图片将作为[备用内容](flow-custom-elements#set-fallback-content)显示。

## 2. 将动画文件添加到应用程序 \{#2-add-the-animation-file-to-your-app\}

原生代码从 iOS 和 Android 项目中读取动画文件，而非从共享代码的 Compose Multiplatform 资源中读取：

- **iOS**：在 Xcode 中将文件添加到应用目标。
- **Android**：将文件放入 `composeApp/src/androidMain/assets`，即 `androidMain` 源码集的 `assets` 文件夹。请将文件保存在该文件夹根目录下，不要放入子文件夹。

文件名去掉 `.json` 后缀后，必须与自定义元素的 ID 一致，例如 `streak_ring` 对应的文件名应为 `streak_ring.json`。

## 3. 创建动画视图 \{#create-the-animation-view\}

创建一个连胜模型和一个播放动画的视图。当连胜数据变化时，你的应用更新模型；视图读取模型，这样打开屏幕时圆环就会显示当前的连胜数。

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift"

// The streak that your app keeps up to date
@MainActor
final class StreakStore: ObservableObject {
    @Published var currentStreak = 0 // days in a row
}

struct StreakRingView: View {
    let animation: LottieAnimation
    @ObservedObject var streakStore: StreakStore

    // 7 days fill the ring: from 0 for an empty ring to 1 for a full one
    private var progress: AnimationProgressTime {
        min(AnimationProgressTime(streakStore.currentStreak) / 7, 1)
    }

    var body: some View {
        LottieView(animation: animation)
            .resizable()
            .playing(.fromProgress(0, toProgress: progress, loopMode: .playOnce))
    }
}
```

`.playing(.fromProgress(0, toProgress: progress, loopMode: .playOnce))` 将动画环从空填充到 `progress` 位置。

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin"

// the streak that your app keeps up to date
class StreakStore {
    val currentStreak = MutableStateFlow(0) // days in a row
}

@Composable
fun StreakRing(animationFile: String, streakStore: StreakStore) {
    val composition by rememberLottieComposition(LottieCompositionSpec.Asset(animationFile))
    val streak by streakStore.currentStreak.collectAsState()

    // 7 days fill the ring: from 0 for an empty ring to 1 for a full one
    val progress = minOf(streak / 7f, 1f)

    LottieAnimation(
        composition = composition,
        modifier = Modifier.fillMaxSize(), // scale the animation to fit the custom element
        clipSpec = LottieClipSpec.Progress(0f, progress),
    )
}
```

`clipSpec = LottieClipSpec.Progress(0f, progress)` 会将圆环从空填充到 `progress` 指定的位置。

</TabItem>
</Tabs>

## 4. 将动画与自定义元素匹配 \{#4-match-the-animation-to-the-custom-element\}

在您的[全局解析器](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk)中，为连续打卡模型添加一个属性。然后为 `lottie_animation` 类型和 `streak_ring` ID 返回动画视图。高亮行显示了需要添加或修改的内容。如果您的应用尚未设置全局[解析器](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views)，可直接复制完整代码：

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift" {6,14-18}

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let streakStore: StreakStore

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "lottie_animation" where id == "streak_ring":
            guard let animation = LottieAnimation.named(id) else {
                return nil // no animation file: show the fallback
            }
            return AnyView(StreakRingView(animation: animation, streakStore: streakStore))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}
```

将 `streak_ring` case 放在其他任何 `lottie_animation` case 之前，因为 Swift 只会执行第一个匹配的 case。如果应用包中没有该 ID 对应的文件，解析器会返回 `nil`，用户将看到备用内容。

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin" {8,22-28}

class CustomElementsResolver(
    context: Context,
    private val streakStore: StreakStore,
) : AdaptyCustomElementsResolver {
    // the animation files in the assets folder, listed once
    private val animationFiles: Set<String> = try {
        context.assets.list("").orEmpty().toSet()
    } catch (e: IOException) {
        emptySet() // no list of files: every Lottie element shows the fallback
    }

    override fun resolve(type: String, id: String): AdaptyCustomElementContent? =
        when (type) {
            "lottie_animation" -> {
                // the ID names the animation file, such as streak_ring.json
                val file = "$id.json"
                when {
                    file !in animationFiles -> null // no file for this ID: show the fallback
                    id == "streak_ring" ->
                        AdaptyCustomElementContent.compose { StreakRing(file, streakStore) }
                    // the other animations of your resolver
                    else -> null
                }
            }
            // the other Types of your resolver
            else -> null
        }
}
```

如果 `assets` 文件夹中没有对应 ID 的文件，解析器会返回 `null`，用户将看到备用内容。如果你的解析器已经为[每个动画文件返回一个视图](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views)，当 ID 不是 `streak_ring` 时，返回该视图而非 `null`。这样，用户仍然可以看到其他 `lottie_animation` 自定义元素的动画效果。

</TabItem>
</Tabs>

创建包含打卡模型的解析器，并在应用启动时将其设置为全局解析器：

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

在 `iOSApp.swift` 中，向 `AppDelegate` 类添加一个连续签到模型的属性，并在 `application(_:didFinishLaunchingWithOptions:)` 方法中设置解析器。高亮行为需要新增的内容，`AppDelegate` 类的其余部分保持不变：

```swift showLineNumbers title="iosApp/iosApp/iOSApp.swift" {1,5-6,12}

class AppDelegate: UIResponder, UIApplicationDelegate {
    // the streak model that your app updates
    let streakStore = StreakStore()

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(streakStore: streakStore))
        // the rest of your launch code
        return true
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

在 `MainApplication.kt` 中，为连续打卡模型添加一个属性，并在 `onCreate` 方法中设置解析器。高亮行显示需要添加的内容。其余 `MainApplication` 类保持不变：

```kotlin showLineNumbers title="MainApplication.kt" {7-8,12}
package com.example.app

class MainApplication : Application() {
    // the streak model that your app updates
    val streakStore = StreakStore()

    override fun onCreate() {
        super.onCreate()
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, streakStore))
    }
}
```

</TabItem>
</Tabs>

## 5. 从共享代码中发送连续天数 \{#5-send-the-streak-from-your-shared-code\}

你的共享代码负责维护连续天数，而各平台的原生视图则从连续天数模型中读取它。共享代码无法直接调用 Swift 代码或 `MainApplication` 类。要更新模型，需要在共享代码中声明一个接口，并在每个平台的连续天数模型中分别实现它。

在 `commonMain` 中，声明该接口，以及一个持有当前平台连续天数模型的对象：

```kotlin showLineNumbers title="commonMain"
// the streak model of each platform implements this interface
interface StreakReceiver {
    fun setStreak(days: Int)
}

object StreakBridge {
    // the platform code sets the receiver at app launch
    var receiver: StreakReceiver? = null

    // call at app launch, and each time the streak changes
    fun sendStreak(days: Int) {
        receiver?.setStreak(days)
    }
}
```

在每个平台的连续天数模型中实现该接口，并在应用启动时将该模型设置为接收者：

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

让 `StreakStore` 遵循来自共享框架（如 `ComposeApp`）的 `StreakReceiver` 协议。Kotlin/Native 会将 Kotlin 的 `Int` 类型映射为 Swift 中的 `Int32`。高亮行为需要添加的内容：

```swift showLineNumbers title="Swift" {1,5,8-13}

// The streak that your app keeps up to date
@MainActor
final class StreakStore: ObservableObject, StreakReceiver {
    @Published var currentStreak = 0 // days in a row

    // your shared code can call this method on any thread
    nonisolated func setStreak(days: Int32) {
        Task { @MainActor in
            self.currentStreak = Int(days)
        }
    }
}
```

在 `AppDelegate` 类的 `application(_:didFinishLaunchingWithOptions:)` 方法中，在 resolver 之后，将 streak 模型设置为接收器：

```swift showLineNumbers title="iosApp/iosApp/iOSApp.swift" {2}
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(streakStore: streakStore))
StreakBridge.shared.receiver = streakStore
```

在 `iOSApp.swift` 中也导入 `ComposeApp`。

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

让 `StreakStore` 实现 `StreakReceiver` 接口。高亮行为需添加的内容：

```kotlin showLineNumbers title="Kotlin" {2,5-7}
// the streak that your app keeps up to date
class StreakStore : StreakReceiver {
    val currentStreak = MutableStateFlow(0) // days in a row

    override fun setStreak(days: Int) {
        currentStreak.value = days
    }
}
```

在 `MainApplication` 类的 `onCreate` 方法中，在解析器之后立即将连续记录模型设置为接收器：

```kotlin showLineNumbers title="MainApplication.kt" {2}
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, streakStore))
StreakBridge.receiver = streakStore
```

</TabItem>
</Tabs>

在您的共享代码中，请在应用启动时以及每次连续登录天数发生变化时调用 `StreakBridge.sendStreak`。如果共享代码在平台代码设置接收器之前发送了连续登录天数数据，该数据将无法到达模型。

## 6. 在设备上测试 \{#test-on-a-device\}

流程与付费墙编辑工具无法运行您的应用代码，因此画布上只显示备用内容。如需预览动画：

1. [发布流程](builder-save-publish)。若要查看最新发布版本而非缓存版本，请将设备注册为[测试设备](test-devices)。
2. 运行包含 resolver 的应用构建版本。将连续天数设为 0 天，打开界面，验证圆环保持空心状态。分别设为 4 天和 7 天后重复操作，验证圆环是否填充至对应值。

如需测试备用内容，请从构建版本中移除动画文件，然后再次打开界面。

如需了解为何显示备用内容而非动画，请按照 Kotlin Multiplatform 指南中[在设备上测试](kmp-flow-custom-elements#test-on-a-device)部分的说明进行操作。