A Guide to Lottie in HarmonyOS
Tags: opensource, java, distributedsystems
Published: 2022-03-08 09:42:12

## Introduction

I can hardly imagine any application without animations, fancy designs, at least there is one component on the screen which is interactive. This boils down to one aspect which is the **User Experience** which is key factor to be considered while designing apps.


![Animation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mfyx072pdfeqco41u6ai.gif)

> User experience encompasses of all aspects of the end-user’s interaction with the company, its services, and its products
 — Don Norman, Cognitive Scientist & User Experience Architect

As a developer the vital role is in Architecting, deriving the functionalities and many more on top of this focusing on the design aspects becomes tedious.

Thanks to libraries like Lottie which is a full-fledged one such library to provide Animation effortlessly in your application with few initial setup.


![Lottie](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dygzbqlzzswtsxgixq61.gif)

---

## Lottie

If you haven't heard about Lottie, then let's understand what is this library and its features.

- Lottie is a library that can be used on website or mobile application for adding animations.

- It is a one stop solution for animation and it’s perfect for developers as you just have to add a few lines of code and you are good to go, isn’t it amazing.

- Lottie is a library for Android, iOS, Web, and Windows that parses Adobe After Effects animations exported as json with [Bodymovin](https://github.com/airbnb/lottie-web) and renders them natively on mobile and on the web!

- 

More info on Lottie can be found [here](https://airbnb.io/lottie/#/).


![Lottie](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kznajd144qbwu9d3hfk3.gif)

Are we using Lottie just for animation or does it have more features with this pack, I have listed few of them below.

- Create, edit, and ship in a few clicks.
- We can eliminate long codes, just implement the animation and the rest is taken take by the library.
- Compatible with all browsers.
- It is seemingly ease to use.

It is an ideal choice to create an engaging user experience with animations then Lottie is the go to library or tool.

---

Since we have gathered loads of information about Lottie, now let's see how to use Lottie in your **HarmonyOS Mobile App** and process or setup required.

If you are new to **HarmonyOS **then do checkout the articles about HarmonyOS [here](https://medium.com/application-library-engineering-group/why-harmonyos-52777e74637e).

More info on the Lottie library can be found [here ](https://github.com/applibgroup/Lottie-ohos)

## Step by Step Implementation

## 1.DevEco Studio
Here we would be using **DevEco studio** IDE which is designed exclusively to run HarmonyOS applications, if you haven't installed one then you can get it from the official link with the SDK. Also, we have a step by step instructions for the environment setup available [here](https://developer.harmonyos.com/en/develop/deveco-studio).

## 2.Project Creation
Once you have the DevEco Studio up running you can create a select a **"File" -> New -> New Project Option, **then you are presented with multiple templates to choose from, select the template as shown below which is Empty Ability.

![DevEcoStudio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73c1ysleikb673xru1rx.png)

As a next step you will have to "**Configure the Project**" with the project details, path and ensure to select 

- Language as Java and
- API version to 5

![Project creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0dbud4nw00dn85rwwlb5.png)
 
After the initial setup you are ready to start working on the application.

## 3.Dependency
 Next add the Lottie Dependency, in order to use the library in your HarmonyOS mobile app, you need to first install it by adding the below dependency in your entry/build.gradle file.

```
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.har'])
    implementation 'io.openharmony.tpc.thirdlib:lottie-ohos:1.0.4'
}
```

## 4.Network settings
Navigate to resources -> config.json and add the below lines of code to access internet.

```
{
  "app": {
    "bundleName": "com.airbnb.lottie.demo",
    "vendor": "airbnb",
    "version": {
      "code": 1000000,
      "name": "1.0.0"
    }
  },
  "deviceConfig": {},
  "module": {
    "package": "com.airbnb.lottie.demo",
    "name": ".Lottie",
    "reqCapabilities": [
      "video_support"
    ],
    "deviceType": [
      "default",
      "tablet"
    ],
    "distro": {
      "deliveryWithInstall": true,
      "moduleName": "entry",
      "moduleType": "entry",
      "installationFree" : true
    },
    "abilities": [
      {
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ],
        "orientation": "portrait",
        "name": "com.airbnb.lottie.demo.MainAbility",
        "icon": "$media:icon",
        "description": "$string:mainability_description",
        "label": "$string:app_name",
        "type": "page",
        "launchType": "standard"
      }
    ],
    "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET",
        "reason": "get right",
        "usedScene": {
          "ability": [
            "com.airbnb.lottie.demo.MainAbility"
          ],
          "when": "always"
        }
      }
    ]
  }
}
```

5. In HarmonyOS loading Lottie animations are simple and this requires 3 step process as listed below.

1. The String URL — The URL is passed as parameter to the setFilename() function which needs to be loaded.

2. The Repeat Count — Passed setRepeatCount the function.Lottie library should display animation according to the repetition count specified.

3. The Target — Passed through the setAnimationData() function. This parameter will represent the LottieAnimationView components and Targets where your Lottie animation is assumed to be displayed in.

6.Implementation - Here we are loading an Lottie json found on the internet in an LottieAnimationView component:

- let's define the layout file, you can find the layout by navigating to the below path **"entry" -> src-> resources ->base -> layout ->animation_slice.xml**

```
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <com.airbnb.lottie.LottieAnimationView
        ohos:id="$+id:animationView"
        ohos:width="match_parent"
        ohos:height="match_parent"/>
</DirectionalLayout>
```
NOTE: the LottieAnimationView are present in the resource/raw folder, you can refer this [link ](https://github.com/applibgroup/Lottie-ohos/tree/main/entry/src/main/resources/rawfile)for further details.

## 7. Get the reference to LottieAnimationView Component

```
//Initialize LottieAnimationView Component

     LottieAnimationView lv = (LottieAnimationView)rootLayout.findComponentById(ResourceTable.Id_animationView);

```

## 8.Loading lottieJson present in server

Now that you have the reference of the LottieAnimationView component, you can write code to load animation into LottieAnimationView component.

```
private void initLottieViews(String string, String bundleKey, int repeatCount) {
        L.setTraceEnabled(true);
        LottieAnimationView lv = (LottieAnimationView)rootLayout.findComponentById(ResourceTable.Id_animationView);
        lv.setContentPosition((float)50.0,(float)50.0);
        LottieAnimationViewData data = new LottieAnimationViewData();
        if(bundleKey.equals(KEY_JSON_STRING) && string!=null) {
            data.setFilename(string);
        }
        else {
            data.setUrl(string);
        }
        data.setRepeatCount(repeatCount);
        data.autoPlay = true;
        lv.setAnimationData(data);
    }
```
You can find the above code [here](https://github.com/applibgroup/Lottie-ohos/blob/main/entry/src/main/java/com/airbnb/lottie/slice/AnimationSlice.java)

---

List of public APIs for app-developer
The public methods below will help us to operate on the component at runtime.
 

- setContentPosition(float x, float y)
- setAnimationData(LottieAnimationViewData data)
- setRepeatCount(int count)
- setFilename(String name)
- setUrl(String url)
- setResId(int id)

---
Now let's see couple examples of loading Animation from different Source.

## 1. Loading Lottie animation from folder.

In this example we will load the Lottie animation which is stored in the res/raw folder. you can refer this [link ](https://github.com/applibgroup/Lottie-ohos/tree/main/entry/src/main/resources/rawfile)for further details.

Layout.xml:
```

<com.airbnb.lottie.LottieAnimationView
        ohos:id="$+id:animationView"
        ohos:width="match_parent"
        ohos:height="match_parent"/>
```
Java Slice:

```
LottieAnimationViewData data = new LottieAnimationViewData();
data.setUrl(string);
data.setRepeatCount(repeatCount);
data.autoPlay = true;
lv.setAnimationData(data);

```

![Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4jzt8uhr3wl26w64kms.gif)

---

2. Loading Lottie from URL

You can refer [here ](https://github.com/applibgroup/Lottie-ohos/blob/main/entry/src/main/java/com/airbnb/lottie/slice/UrlLoadSlice.java)how is the URL loaded and used.

Layout.xml:

```
<com.airbnb.lottie.LottieAnimationView
        ohos:id="$+id:animationView"
        ohos:width="match_parent"
        ohos:height="match_parent"/>
```
Java Slice:

```
LottieAnimationViewData data = new LottieAnimationViewData();
         data.setUrl(stringURL);
        data.setRepeatCount(repeatCount);
        data.autoPlay = true;
        lv.setAnimationData(data);
```

![Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqypsvlbi2cm0djefbfs.gif)

---

## **Conclusion**

So in this post you must have got a understanding how user 
experience play a vital role and how Lottie comes to rescue in giving this wonderful full pack collection of amazing animations.

Later on we also saw how we could implement Lottie animations in HarmonyOS easily from URL or locally stored.

More info on the Lottie library can be found [here ](https://github.com/applibgroup/Lottie-ohos)