---
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 Capacitor SDK 4.4 或更高版本。早期 SDK 版本会为每个自定义元素显示[备用内容](flow-custom-elements#set-fallback-content)。
- 设置您的应用以[获取](capacitor-get-pb-paywalls)和[展示](capacitor-present-paywalls)流程。
- 按照 [Capacitor 指南](capacitor-flow-custom-elements#before-you-start)为自定义元素配置应用的原生代码。
- 在 iOS 上，通过 Swift Package Manager 将 Lottie 添加到 Xcode 中的应用目标，地址为 `https://github.com/airbnb/lottie-spm.git`。
- 在 Android 上，[配置您的 Android 项目](capacitor-flow-custom-elements#set-up-your-android-project)，包括 Jetpack Compose。本示例中的动画视图是一个 composable。通过 Gradle 将 Compose Foundation 添加到应用，依赖为 `androidx.compose.foundation:foundation`，无需指定版本（版本由 `io.adapty:android-ui` 的 Compose BOM 统一管理）。同时添加适用于 Jetpack Compose 的 Lottie，依赖为 `com.airbnb.android:lottie-compose`。

准备一个 `.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 项目中读取动画文件，而非从 Web 应用的 assets 目录中读取：

- **iOS**：在 Xcode 中将文件添加到应用的 target。
- **Android**：将文件放在 `android/app/src/main/assets` 目录下，即 Android 应用模块的 `assets` 文件夹。请将其放在该文件夹的根目录，而非子文件夹中。

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

## 3. 创建动画视图 \{#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. 将动画与自定义元素关联 \{#match-the-animation-to-the-custom-element\}

在你的[全局解析器](capacitor-flow-custom-elements#pass-the-resolver-to-the-sdk)中，为连胜模型添加一个属性。然后为 `lottie_animation` 类型和 `streak_ring` ID 返回动画视图。高亮行显示了需要添加或修改的内容。如果你的应用还没有全局[解析器](capacitor-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`，用户将看到备用内容。如果你的解析器已经为[每个动画文件返回了对应视图](capacitor-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>

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

```swift showLineNumbers title="ios/App/App/AppDelegate.swift" {1,9-10,13}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    // 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. 从 JavaScript 代码发送连续打卡天数 \{#send-the-streak-from-your-javascript-code\}

你的 JavaScript 代码负责维护连续打卡天数，原生视图从 streak 模型中读取该数值。要更新模型，需要通过<InlineTooltip tooltip="本地 Capacitor 插件">[iOS](https://capacitorjs.com/docs/ios/custom-code)、[Android](https://capacitorjs.com/docs/android/custom-code)</InlineTooltip>将连续打卡天数发送到原生代码。该插件为每个平台提供了独立实现，并提供一个 JavaScript 接口。

为每个平台实现插件：

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

在 Xcode 的 `App` 目标中创建插件，它会在你的 `AppDelegate` 类中更新连续打卡模型：

```swift showLineNumbers title="StreakStorePlugin.swift"

@objc(StreakStorePlugin)
public class StreakStorePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "StreakStorePlugin"
    public let jsName = "StreakStore"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "setStreak", returnType: CAPPluginReturnPromise)
    ]

    @objc func setStreak(_ call: CAPPluginCall) {
        let days = call.getInt("days") ?? 0
        Task { @MainActor in
            (UIApplication.shared.delegate as? AppDelegate)?.streakStore.currentStreak = days
        }
        call.resolve()
    }
}
```

创建 `CAPBridgeViewController` 的子类，并在其 `capacitorDidLoad` 方法中注册插件。如果你的应用已经有 `CAPBridgeViewController` 的子类，直接在那里注册即可：

```swift showLineNumbers title="MyViewController.swift"

class MyViewController: CAPBridgeViewController {
    override open func capacitorDidLoad() {
        bridge?.registerPluginInstance(StreakStorePlugin())
    }
}
```

要让应用使用此子类，请在 `SceneDelegate.swift` 中将 `CAPBridgeViewController()` 替换为 `MyViewController()`。如果你的项目没有 `SceneDelegate.swift`，则在 `Main.storyboard` 中将 **Bridge View Controller** 的自定义类设置为 `MyViewController`，详见 [Custom ViewController](https://capacitorjs.com/docs/ios/viewcontroller)。

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

在 `MainActivity.java` 所在的文件夹中创建插件。它会更新 `MainApplication` 类中的连胜记录模型：

```kotlin showLineNumbers title="StreakStorePlugin.kt"
package com.example.app

@CapacitorPlugin(name = "StreakStore")
class StreakStorePlugin : Plugin() {
    @PluginMethod
    fun setStreak(call: PluginCall) {
        val app = context.applicationContext as MainApplication
        app.streakStore.currentStreak.value = call.getInt("days") ?: 0
        call.resolve()
    }
}
```

要注册插件，在 `MainActivity.java` 中，于 `super.onCreate` 之前调用 `registerPlugin`。高亮行为需要添加的内容：

```java showLineNumbers title="MainActivity.java" {3,7-11}
package com.example.app;

public class MainActivity extends BridgeActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        registerPlugin(StreakStorePlugin.class);
        super.onCreate(savedInstanceState);
    }
}
```

</TabItem>
</Tabs>

在 JavaScript 代码中注册插件，然后在应用启动时以及每次连续天数发生变化时发送连续天数：

```typescript showLineNumbers title="sendStreak.ts"

interface StreakStorePlugin {
  setStreak(options: { days: number }): Promise<void>;
}

// the name matches the jsName on iOS and the plugin name on Android
const StreakStore = registerPlugin<StreakStorePlugin>('StreakStore');

// call at app launch, and each time the streak changes
export async function sendStreak(days: number) {
  await StreakStore.setStreak({ days });
}
```

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

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

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

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

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