- Getting Started with Lottie Animations (Android)
- Select an Animation
- Fire up Android Studio
- Get. Set. CODE!!
- How to Control Lottie Animations Programmatically in Android?
- Steps to Control Lottie Animations
- Анимация в мобильных приложениях: тестируем Lottie
- Разбираемся в нюансах
- Создаем Lottie-файлы
- Подключаем библиотеку
- Что новенького
- На практике?
- Blog / Working With Lottie
- Getting Started with Lottie Animations in an Android App
- 1. Choose your Lottie
- 2. Setup your project
- Add LottieAnimationView to your layout
- Bundling animations with your app
Getting Started with Lottie Animations (Android)
Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as json with Bodymovin and renders them natively on mobile!
You can create your own animations using Adobe After Effects, or feel free to use the ones uploaded by other users on https://lottiefiles.com/
For this tutorial, we will be using one of the already uploaded animations. Without further ado, let’s get started 😉
Select an Animation
- Go to https://lottiefiles.com/ and select any animation of your choice. For this example, I’m going to choose 3 different animations:-
https://lottiefiles.com/3269-thumbup,
https://lottiefiles.com/434-gradient-animated-background, and
https://lottiefiles.com/440-stop-go-radio-button - Download the animations and rename them. For example, the ones used here were renamed to “thumb_up.json”, “gradient_bg.json” and “toggle_switch.json” respectively.
Fire up Android Studio
2. Select Empty Activity.
3. Name your application. In this example, I’ve decided to go with LottiePlayground. Please ensure that the “ Use AndroidX artifacts” feature has been enabled. Click on Finish.
4. Once the project is completely loaded, go to app-level Gradle file and under dependencies, add
At the time of writing the latest version of Lottie is ‘ 3.5.0’.
5. Sync the project Gradle files.
6. Create a folder “ assets” under app > src > main and paste the downloaded animations in it.
Get. Set. CODE!!
2. Modify your styles.xml:
3. Modify your AndroidManifest.xml:
4. Write the following code in activity_main.xml:
5. Write the following code in MainActivity.java:
Well, that’s pretty much it. Hit that ‘Run app’ button, then sit back while the code compiles and the APK installs on your device.
Источник
How to Control Lottie Animations Programmatically in Android?
Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as JSON with Bodymovin and renders them natively on mobile. The Lottie animations are free to use vector animation files. Many famous applications use this such as Uber, Netflix, Google, Airbnb, Shopify, etc. Using Lottie, one can put animations inside a mobile (Android/iOS) application and even control them. Through this article, we would like to share with you the implementation of a method to control a JSON animation in Android using Lottie. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Note: To use Lottie Animation in Android please refer to How to add Lottie Animation in an Android app
Steps to Control Lottie Animations
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add library to the build.gradle file
For implementing an animation using Lottie, first, implement a dependency implementation ‘com.airbnb.android:lottie:$lottieVersion’ into the build.gradle file of the app. The latest version in October 2020 is 3.4.2, replace $lottieVersion with this value. Now sync the project by clicking the sync option which appears after every change made to the build.gradle file. Remember, build.gradle is always a Groovy or a Kotlin file.
Step 3: Add a lottie animation file to the project
Choose any animation from here and download the JSON file of animation.
Now go to app > res > right-click > New > Folder > Raw Resource Folder and copy the JSON file to this raw folder.
Step 4: Working with the activity_main.xml file
In the activity_main.xml file declare a Lottie object by specifying the parameters. Also declare two Buttons, one to start the animation and one to pause it. The primary parameters are:
- lottie_rawRes: takes in the JSON animation to be displayed.
- lottie_loop: boolean value, that decides if the animation is on loop or not depending upon the boolean value supplied.
- lottie_autoPlay: boolean value, which decides if the animation plays as soon as it is initialized.
It is important to note that the JSON animation should only be kept in a folder named raw under the res folder since the functions are made explicitly to call this file path. And the name of the JSON file should not contain any special character other then ‘_‘.
Источник
Анимация в мобильных приложениях: тестируем Lottie
О библиотеке LottieFiles многие знают, но пробовать на практике не спешат. Статей на эту тему мало, поэтому я решила поделиться своим опытом создания анимации для мобильных приложений с помощью Lottie.
Без анимации в мобильных интерфейсах не обойтись. Она оживляет приложение, помогает пользователю ориентироваться в нем и получать отклик на свои действия, вызывает эмоции.
По типу взаимодействия можно разделить анимацию на несколько категорий:
- микровзаимодействия — визуальные отклики на действия пользователя, анимация конкретных элементов интерфейса на экране, например, кнопки или иконки;
- независимую графическую анимацию в пределах экрана, например, анимированная иллюстрация в онбординге или сплеш-скрине;
- переходы — анимация, связывающая между собой два экрана.
Давайте проясним, для каких типов взаимодействия подходит Lottie.
Разбираемся в нюансах
LottieFiles это библиотека для iOS, Android, Web и Windows. В этой статье расскажу про особенности только для iOS и Android, так как специализируюсь на мобильных интерфейсах.
Маленький ликбез — библиотека состоит из файлов json, в которых закодирована анимация из Adobe After Effect. Плагин, который участвует в создании таких файлов, называется Bodymovin. Он имеет JavaScript движок и рендерит анимацию в режиме реального времени.
Вы можете воспользоваться пробной версией Adobe After Effect, если не работали с этой программой раньше. За неделю использования успеете протестировать и решить, нужна ли она вам.
Я проанализировала таблицу от Airbnb и выделила функции Adobe After Effect, которые поддерживаются и на iOS, и на Android. При создании анимации их нужно учитывать, чтобы получить на выходе json, который будет корректно отображаться на обеих платформах.
Сводная таблица с поддерживаемыми функциями для iOS и Android
Создаем Lottie-файлы
Дизайнер создает анимацию в Adobe After Effect, учитывая ограничения, затем экспортирует ее в json с помощью плагина Bodymovin. После этого нужно сделать тест файла в превью-сервисах — Bodymovin Player или Lottie Preview.
Продумайте анимацию заранее с учетом слоев. Ее можно создать с нуля в Adobe After Effect, а можно сначала отрисовать исходный файл в Adobe Illustrator или Sketch. Импорт в Adobe After Effect в этом случае могут упростить плагины:
- Overlord (от Adam Plouff) для интеграции Adobe After Effect и Adobe Illustrator — для быстрого перемещения векторных форм между программами без импорта и организации файлов;
- AEUX (от Adam Plouff и Google SUMux) — для интеграции Adobe After Effect и Sketch, аналогичен Overlord. Скоро будет доступен для Figma!
Если возможности приобрести плагины нет, то просто импортируйте файл Adobe Illustrator как Composition в Adobe After Effect. До начала работы создайте Shapes из импортированных слоев. Если этого не сделать, то при экспорте json вы потеряете визуальную часть анимации из-за привязки к файлу Adobe Illustrator.
Создание Shapes на основе векторных слоев файла Adobe Illustrator
Я воспользовалась готовыми иллюстрациями и подготовила кейсы, которые опираются на предложенную классификацию анимации. Для примера микровзаимодействия выбрана кнопка, для независимой графической анимации — иллюстрации к онбордингу. Также я попробовала сделать json для визуальной составляющей кастомного перехода между экранами.
Анимация в онбординге (источник изображений — Flaticon)
Анимация кнопки и анимация для перехода между двумя экранами
Подключаем библиотеку
Для того чтобы добавить в приложение анимацию, подключите библиотеку LottieFiles. Здесь можно узнать, как это сделать. В исполняемом коде для анимации можно задать размер, скорость воспроизведения и число проигрываний — это позволяет точнее настроить анимацию.
Все кейсы были протестированы и подключены — Lottie можно использовать для анимации разного назначения.
Подключение Lottie на iOS
Что новенького
Недавно Maxime Robinet совместно с Psycle Research запустили эксперимент Figma(love)Lottie, в котором попробовали использовать API Figma для демонстрации json на макетах.
Чтобы воспользоваться сервисом, проведите предварительные манипуляции с макетом в Figma. Разместите на нем группу слоев: контейнер для отображения анимации, параметры анимации в текстовых блоках (скорость и цикличность воспроизведения). Подробная инструкция тут.
Для демонстрации понадобятся json, персональный токен для доступа (можно получить в настройках аккаунта) и ссылка на макет экрана в Figma. Нужный мокап устройства добавится автоматически под разрешение макета. В итоге у вас получится ссылка, которой можно поделиться. Она будет работать около двух месяцев.
Figma(love)Lottie поможет вам демонстрировать json непосредственно в интерфейсе и производить настройку параметров анимации без помощи разработчика. Lottie Preview и Bodymovin Player лишены этих возможностей.
На практике?
Lottie может ускорить процесс разработки приложения. Время, затраченное на анимацию в проекте, контролируется дизайнером. Он создает, тестирует, настраивает анимацию и передает разработчикам. Функциональные спецификации здесь не требуются. Однако, по разным причинам, не для каждого мобильного приложения уместно подключать LottieFiles. Также команды разработки часто отказываются от этой библиотеки ввиду налаженных внутренних процессов, выходить за рамки которых обычно затруднительно. Хотелось бы попробовать LottieFiles в реальном проекте.
Тут можно скачать созданные мной json-ы и посмотреть их в Lottie Preview.
Само приложение Lottie Preview — iOS и Android
Источник
Blog /
Working With Lottie
Getting Started with Lottie Animations in an Android App
1. Choose your Lottie
Pick the Lottie for your Android app. You may have your own or you may want to select one from the 1000s of Lottie animations available for free on LottieFiles.
It’s important to test your selected Lottie using the LottieFiles app for Android to make sure the animation you’ve chosen will play the same Android as sometimes not all animations are built with features supported in the Lottie Android player.
Just scan the QR code under the animation on LottieFiles with the app to preview the animation.
2. Setup your project
Getting started with Lottie is very straightforward. This guide assumes that you are using Android Studio as your IDE. If you’re using a different IDE, you can still use the same instructions.
From your project structure panel, select your projects build.gradle file and add the following lines inside your dependencies block:
Replace lottieVersion with the latest available.
The latest version is:
Add LottieAnimationView to your layout
The lottie-android library provides a LottieAnimationView which will take care of rendering your animations for you. Add it to your layouts where you want to place your animations.
Bundling animations with your app
If you need your animations to work offline, you can bundle your animations with your application by including them in your projects raw resources.
If your project does not have one, create it by going to File>New>Folder>Raw Resources Folder. If your animation contains images, you can bundle them all together in a .zip with your .json and follow the same procedure.
Download the animation, rename it to animation.json or animation.zip depending on your use-case, and place into your raw resources folder.
Update your layout code to use the bundled animation
Your first Android project with Lottie animations is ready to go! All that’s left for you to do from here is to configure your project further and customize the animation behaviour. The official documentation for lottie-android provides further information on these configurations.
That’s how you get started but there’s so much more you can do. For more tips on how to use Lottie with your projects, check out our blogs on working with Lottie.
Источник