---
title: "Hiển thị tiến trình người dùng bằng Lottie animation"
description: "Hiển thị tiến trình của từng người dùng, chẳng hạn như chuỗi hoạt động hàng ngày, dưới dạng Lottie animation trên màn hình flow."
---

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

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

Làm theo hướng dẫn này để hiển thị tiến trình của người dùng dưới dạng animation Lottie — ví dụ: một vòng tròn tô dần để hiển thị chuỗi ngày liên tiếp. Ứng dụng của bạn sẽ render animation dưới dạng native Lottie view trong một [custom element](flow-custom-elements).

<DocVideo id="custom-element-lottie-demo.mp4" width="300px" alt="Flow hoàn chỉnh: người dùng nhấn See my streak, và ở màn hình tiếp theo, vòng tròn tô dần lên 4 trong 7 ngày." />

## Trước khi bắt đầu \{#before-you-start\}

- Cập nhật ứng dụng của bạn lên Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 hoặc mới hơn. Các phiên bản SDK cũ hơn sẽ hiển thị [nội dung dự phòng](flow-custom-elements#set-fallback-content) cho mọi phần tử tùy chỉnh.
- Thiết lập ứng dụng để [tải](kmp-get-pb-paywalls) và [hiển thị](kmp-present-paywalls) flow.
- Thiết lập code native của ứng dụng cho các phần tử tùy chỉnh, theo [hướng dẫn Kotlin Multiplatform](kmp-flow-custom-elements#before-you-start).
- Trên iOS, thêm Lottie vào app target trong Xcode bằng Swift Package Manager, từ `https://github.com/airbnb/lottie-spm.git`.
- Trên Android, [thiết lập dự án Android của bạn](kmp-flow-custom-elements#set-up-your-android-project), bao gồm cả Jetpack Compose. View animation trong recipe này là một composable. Nếu ứng dụng của bạn không dùng Compose Multiplatform, hãy thêm Compose Foundation vào dependencies của `androidMain`, từ `androidx.compose.foundation:foundation`, không cần chỉ định version. Compose BOM của `io.adapty:android-ui` sẽ quản lý version. Thêm Lottie cho Jetpack Compose từ `com.airbnb.android:lottie-compose`.

Chuẩn bị một animation Lottie ở định dạng `.json`, hoặc tải xuống file mẫu [`streak_ring.json`](https://raw.githubusercontent.com/adaptyteam/adapty-docs/refs/heads/main/Downloads/streak_ring.json). Ứng dụng phát animation từ đầu và dừng lại theo tỷ lệ tiến độ, chẳng hạn dừng ở giữa nếu tiến độ là 50%. Để hiển thị đúng tiến độ, animation cần đáp ứng:

- Không có tiến độ ở frame đầu tiên, và tiến độ đầy đủ ở frame cuối cùng.
- Tốc độ đều, không có easing. Nếu animation bắt đầu chậm rồi tăng tốc, nó sẽ hiển thị ít hơn một nửa tiến độ khi đã đi được nửa chừng.

## 1. Thêm phần tử tùy chỉnh vào màn hình \{#1-add-the-custom-element-to-the-screen\}

Trong Flow & Paywall Builder, [thêm một phần tử tùy chỉnh](flow-custom-elements#add-and-configure) vào màn hình flow, và thiết lập cho animation:

- **Type**: `lottie_animation`.
- **ID**: `streak_ring`. Trong hướng dẫn này, ID cũng là tên của file animation.
- **Height**: Giữ nguyên chiều cao **Fixed** mặc định. Animation sẽ tự co giãn để vừa với phần tử tùy chỉnh.

Bên trong phần tử tùy chỉnh, thêm một [**Image**](custom-media#image) với ảnh tĩnh của vòng tròn. Người dùng sẽ thấy nó như là nội dung [dự phòng](flow-custom-elements#set-fallback-content) khi phiên bản ứng dụng của họ không phát được animation.

## 2. Thêm file animation vào ứng dụng \{#2-add-the-animation-file-to-your-app\}

Code native của bạn đọc file animation từ dự án iOS và Android, không phải từ resources của Compose Multiplatform trong shared code:

- **iOS**: Thêm file vào app target trong Xcode.
- **Android**: Đặt file vào `composeApp/src/androidMain/assets`, tức là thư mục `assets` của source set `androidMain`. Giữ file ở thư mục gốc, không đặt trong thư mục con.

Tên file bỏ phần `.json` phải khớp với ID của custom element, ví dụ `streak_ring.json` tương ứng với `streak_ring`.

## 3. Tạo animation view \{#create-the-animation-view\}

Tạo một model cho streak và một view để phát animation. App của bạn cập nhật model khi streak thay đổi. View đọc model, vì vậy vòng tròn sẽ hiển thị streak hiện tại khi màn hình mở ra:

<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))` điền vào vòng nhẫn một lần, từ trống đến `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)` điền vào vòng tròn một lần, từ trống đến `progress`.

</TabItem>
</Tabs>

## 4. Khớp animation với phần tử tùy chỉnh \{#match-the-animation-to-the-custom-element\}

Trong [resolver toàn ứng dụng](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk) của bạn, hãy thêm một thuộc tính cho streak model. Sau đó trả về animation view cho Type `lottie_animation` và ID `streak_ring`. Các dòng được tô sáng cho thấy những gì cần thêm hoặc thay đổi. Nếu ứng dụng của bạn chưa có [resolver](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) toàn ứng dụng, hãy sao chép toàn bộ đoạn code:

<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
        }
    }
}
```

Đặt case `streak_ring` trước bất kỳ case `lottie_animation` nào khác, vì Swift chỉ chạy case đầu tiên khớp. Nếu bundle ứng dụng không có file nào cho ID đó, resolver trả về `nil` và người dùng sẽ thấy fallback.

</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
        }
}
```

Nếu thư mục `assets` không có tệp nào cho ID đó, resolver sẽ trả về `null` và người dùng sẽ thấy phần dự phòng. Nếu resolver của bạn đã trả về [view cho mọi tệp animation](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views), hãy trả về view đó thay vì `null` khi ID không phải là `streak_ring`. Như vậy, người dùng vẫn thấy được các animation của các phần tử tùy chỉnh `lottie_animation` khác.

</TabItem>
</Tabs>

Tạo resolver với streak model, và đặt nó làm resolver toàn ứng dụng khi khởi chạy:

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

Trong `iOSApp.swift`, thêm một thuộc tính cho streak model vào class `AppDelegate` của bạn, và thiết lập resolver trong phương thức `application(_:didFinishLaunchingWithOptions:)`. Các dòng được highlight cho thấy những gì cần thêm. Giữ nguyên phần còn lại của class `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)">

Trong `MainApplication.kt`, thêm một thuộc tính cho streak model, và thiết lập resolver trong phương thức `onCreate`. Các dòng được highlight cho thấy những gì cần thêm. Giữ nguyên phần còn lại của class `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. Gửi streak từ shared code của bạn \{#5-send-the-streak-from-your-shared-code\}

Shared code của bạn lưu trữ streak, và các native view đọc dữ liệu đó từ streak model. Shared code không thể gọi trực tiếp vào Swift code hay class `MainApplication`. Để cập nhật model, hãy khai báo một interface trong shared code, rồi implement nó trong streak model của từng nền tảng.

Trong `commonMain`, khai báo interface và một object để giữ streak model của nền tảng hiện tại:

```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)
    }
}
```

Triển khai interface trong model streak của từng nền tảng, và đặt model đó làm receiver khi khởi động ứng dụng:

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

Làm cho `StreakStore` tuân thủ giao thức `StreakReceiver` từ shared framework của bạn, chẳng hạn như `ComposeApp`. Kotlin/Native ánh xạ kiểu `Int` của Kotlin sang `Int32` trong Swift. Các dòng được tô sáng là phần cần thêm vào:

```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)
        }
    }
}
```

Trong phương thức `application(_:didFinishLaunchingWithOptions:)` của lớp `AppDelegate`, hãy đặt streak model làm receiver, ngay sau resolver:

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

Import `ComposeApp` trong `iOSApp.swift` nữa.

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

Cho `StreakStore` implement interface `StreakReceiver`. Các dòng được highlight cho thấy những gì cần thêm:

```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
    }
}
```

Trong phương thức `onCreate` của class `MainApplication`, hãy đặt streak model làm receiver, ngay sau resolver:

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

</TabItem>
</Tabs>

Trong code dùng chung, hãy gọi `StreakBridge.sendStreak` khi khởi động ứng dụng và mỗi khi streak thay đổi. Một streak mà code dùng chung gửi đi trước khi platform code thiết lập receiver sẽ không đến được model.

## 6. Kiểm tra trên thiết bị \{#test-on-a-device\}

Flow & Paywall Builder không thể chạy code của ứng dụng, vì vậy canvas chỉ hiển thị fallback. Để xem trước animation:

1. [Xuất bản flow](builder-save-publish). Để xem phiên bản đã xuất bản mới nhất thay vì phiên bản được lưu trong bộ nhớ đệm, hãy đăng ký thiết bị làm [thiết bị thử nghiệm](test-devices).
2. Chạy bản build của ứng dụng có chứa resolver. Đặt streak về 0 ngày, mở màn hình và xác nhận rằng vòng tròn vẫn trống. Lặp lại với 4 và 7 ngày, và xác nhận rằng vòng tròn được tô đầy đến từng giá trị tương ứng.

Để kiểm tra fallback, hãy xóa file animation khỏi bản build và mở lại màn hình.

Để tìm hiểu lý do tại sao paywall dự phòng xuất hiện thay vì animation, hãy làm theo hướng dẫn trong phần [Kiểm tra trên thiết bị](kmp-flow-custom-elements#test-on-a-device) của hướng dẫn Kotlin Multiplatform.