Android app opening animation

Анимации в Android по полочкам (Часть 1. Базовые анимации)

Сегодня я хочу немного рассказать про анимацию в Android. Думаю для всех достаточно очевидный факт, что анимации могут украсить наше приложение. Но я считаю, что они могут намного больше. Первое это — хорошие анимации даже при скромной графике могут вывести наше приложение на абсолютно новый уровень. Второе — это дополнительный инструмент для общения с пользователем, позволяющий фокусировать внимание, подсказывать механики приложения, и многое другое… но это отдельная большая тема.

Сегодня мы поговорим об инструментах для создания анимации. К сожалению, так получилось, что в Android достаточно много способов что либо анимировать, и по началу в них очень легко запутаться. Я постараюсь привести максимально общую классификацию и оставлю ссылки исключительно на документацию, т.к. туториалов можно найти предостаточно. Надеюсь эта статья поможет уложить в голове всё по полочками и, при необходимости создать анимацию, выбрать наиболее подходящий способ.

Часть 1. Базовые анимации
Часть 2. Комплексные анимации
Часть 3. «Низкоуровневые» анимации

Часть 1. Базовые анимации

1. Кадр за кадром

Предполагаю, что первая анимация в мире создавалась именно так, и в Android до сих пор доступна эта возможность.

Всё что нужно сделать это создать xml со ссылками на каждый кадр:

И запустить анимацию (Здесь и далее все примеры будут приведены на Kotlin):

Сложные по графике анимации, небольших размеров и подготовленные во внешнем редакторе.

Возможность достичь любой сложности эффектов

Большое потребление ресурсов и, как следствие, довольно затратный импорт в приложение с возможностью получить OutOfMemory. Если по каким-то причинам вам нужно показывать большое количество кадров, то придётся писать свою реализацию с постепенной подгрузкой изображений в память. Но если так пришлось делать, возможно проще прибегнуть к видео?

2. Анимация свойств объекта (aka Property Animator)

Если нам нужно всего-лишь передвинуть что-нибудь на несколько пикселей в сторону или изменить прозрачность, чтобы не плодить миллион очень похожих друг на друга кадров на помощь приходит Animator. Фактически с помощью него можно анимировать любое свойство любых объектов.

Базовый абстрактный класс называется Animator, у него есть несколько наследников, нам важны:

ValueAnimator — позволяет анимировать любое свойство
ObjectAnimator — наследуется от ValueAnimator и имеет упрощённый интерфейс для анимации свойств View.
ViewPropertyAnimator — Предоставляет ещё один удобный интерфейс для анимации View. Не унаследован от Animator и используется в методе View::animate()

Анимацию выше можно описать как в коде:

так и в XML ( animator/open_animator.xml ):

Так-же есть возможность описать нашу анимацию переходов между стейтами View, что соответсвенно, с лёгкостью позволит создать анимированные переходы между стейтами у любых View. Описанная в XML анимация будет автоматически запущена при смене состояния View.
animator/state_animator.xml

Анимация View объектов и любых их параметров
Анимация любых других параметров

В некоторой степени требовательны к ресурсам

3. Анимация View (aka View animation)

До появления Animator в Android были только Animations. Основной недостаток которых был в том что они анимировали только представление вида и никак на самом деле не изменяли его свойства. Поэтому если хочется анимировать перемещение какого-либо элемента, то дополнительно по окончанию анимации нужно изменить ещё его свойства. Такой подход так или иначе не очень удобен, если вам нужна чуть более сложная анимация или нужно отлавливать нажатия в момент анимации.

Анимацию можно запустить как в коде:

так и в XML (обратите внимание, что синтаксис отличается от xml для Animator):
anim/open_animation.xml

Там, где API не позволяет использовать Animator.

Устаревший API, меняет только представление вида.

4. Анимация векторных ресурсов (aka AnimatedVectorDrawable)

На мой взгляд самая интересная часть в Android анимациях. Можно относительно малыми силами добиваться сложных и интересных эффектов. Трансформации иконок в Android сделаны именно так.

VectorDrawable состоит из Path и Group элементов. Создание анимации сводится к тому, чтобы прописать движение к этим элементам. Андроид на картинке выше, в коде будет выглядеть так:

Чтобы не писать XML вручную можно воспользоваться онлайн инструментом.

Читайте также:  Микрофон usb для андроида

Начиная с API 25 векторные анимации отрисовываются в RenderThread, поэтому, даже если мы загрузим чем-то наш UI Thread (но мы же никогда так не делаем, да?), анимации всё равно будут проигрываться плавно.

Иконки
Анимационные эффекты

Нет возможности вручную управлять точкой анимации во времени (т.е. фактически отсутствует какой-либо метод, вроде setCurrentTime)

Источник

Smooth loading animations in Android

RxJava can seem removed from the world of user experience. It’s easy to think of it as a tool for back-end only. Today we’ll look at a real front-end problem, how to apply marble diagrams to solve it, and how to use Kotlin to clean up the solution. We’ll also look at the difference between throttling and debouncing, and some lesser-know overloads of debounce and delay .

The UX problem

We’re often trying to avoid flicker and flashes on Android apps. One common scenario where this can occur is loading from an API call. We want to show a loading animation if the API call takes too long. But if the API call is almost instantaneous, we don’t want to flicker between a quick loading animation and the content of the page.

There are some existing tools for getting around this, for example the ContentLoadingProgressBar in the Android SDK. Of course, top-tier apps have placeholder views instead of progress bars:

These types of views are best composed in a RecyclerView. The RecyclerView will manage the scheduling of UI updates to avoid the jarring effect when a View is suddenly inserted into a ViewGroup. But this is often not enough to prevent a flicker, flash, or jarring animation:

Since we’re just putting a data into a RecyclerView.Adapter , how do we avoid the flicker of a loading animation for a quick load?

The current feature is a suburb picker to specify pickup location for users selling items on Trade Me.

In the implementation, the Fragments are humble views that simply subscribe to streams of content when they come into focus. The Activity publishes the content for the display, with the Fragment simply subscribing to updates in content. Note the publisher here could also be a ViewModel or a controller Fragment.

Since the published content is received as a reactive streams, we should easily be able to find a combinator on Observable to remove the flicker.

Two false starts

Observable#throttleLast seems like a good candidate. Looking at the above marble diagram, imagine that:

  • the red marble represents our “still loading” state
  • the orange marble represents our loaded state
  • the other colored marbles represent UI updates from user interactions

Intervals of the delay parameter are represented by the clocks on the diagram.

The marbles at the top represent a stream of events as input into the box, with time flowing from left to right. The box is a function on Observable and the marbles at the bottom represent the resultant stream of events after the function has been applied.

Since the red marble (loading) was emitted before the tick of the clock, it is ignored and only the orange marble (loaded) is emitted.This is similar to the result we want: if the loading state is too quick we want it to be dropped and invisible to the user.

However, throttleLast is not quite right for the subsequent events. Imagine that the yellow and green marbles are events triggered by a user interaction e.g., clicking one of the items in the RecyclerView .

The yellow marble is ignored, which may be desirable since it occurred quite quickly before the green one. But the emission of the green marble is delayed until another tick of the clock. This is not what we want — we would prefer the green marble to be emitted immediately so that there is no delay between the user interaction (the click) and the result on screen (the change in the UI).

Since we’ve ruled out Observable#throttleLast , why not look at Observable#debounce ? This certainly sounds more like what we want to achieve. The first overload has a signature that looks like this:

The marble diagram looks like this:

Just from the diagram, we can see that the marbles are only being emitted after the tick of the clock. This is the same mismatch of use case we found for throttleLast .

What we really want is something that can debounce only in the case of loading, and leaves the other marbles to fall immediately.

Читайте также:  Word 2010 для андроида

A promising solution

Turns out there is an overload of debounce that achieves just this:

The combinator in the box shows three arrows of lengths 1, 2, and 3 for f(1) , f(2) , and f(3) . These represent three different debounce intervals. This shows we can achieve debouncing determined by a function, closer to what we want.

A concrete example is found in this Stack Overflow answer by Lawrence Kesteloot:

This clearly explains the parameter debounceSelector : it’s a function that takes as input T and outputs an Observable representing a debounce interval.

Now we can do this:

We can use the Extract Method refactor and type aliases to make this a little bit cleaner:

If it’s something we might use in more than a few places in the app, we could easily write an extension method to take the abstraction further:

Then we can use it like this:

We can write unit tests against the extension function using the TestScheduler since it allows fast-forwarding of time to see which elements have been emitted. We can also use an overload of Observable#delay to prepare the test data. It’s very similar to the overload of Observable#debounce we were using earlier:

The complete set of unit tests is below. Note how we can model our use cases exactly:

The final feature without flicker:

David Rawson is an Android Developer at Trade Me. You can find him on Stack Overflow here.

Default to Open

Life lives here. Stories about how we’re building Trade Me.

Источник

19 Best Android Animation UI/UX Libraries

Mobile applications are getting less static. Interface animations are becoming an integral part of modern apps, making them more user-friendly and navigation through them simpler.

Android projects could use animations for several purposes, specifically to:

  • display application status, since the user would be pleased to receive a response to actions he/she triggers. Besides, an appropriate animation would brighten up the user’s expectation when the page content is updated;
  • connect various phases of a multiphase process, thereby allowing for a smooth transition between the steps and seamless interaction with the user;
  • embed new elements, fitting them harmoniously into the content;
  • simplify the interaction process, informing the user what he/she is going through at the moment.

Animations serve to reinforce the user’s action. Nevertheless, rather fanciful or complex effects distract and confuse him/her. As a result, developers should always maintain the golden medium.

Thus, the more you know about animation UI/UX libraries for the Android platform, the easier it is for you to apply them in a smart way. So, shall we start?

1. AndroidViewAnimations

We will begin with AndroidViewAnimations. It is a simple Android library that enables you to create view shake animations. Its developer was inspired by an iOS library, since Android had no analogue at that time. The library allows you to implement a wide variety of animations, including:

Moreover, each item has its own subsections with different effects.

2. ListViewAnimations

ListViewAnimations is another open source library that enables developers to create ListViews with animations. It has the following features:

  • appearance animations for items in ListViews, GridViews, other AbsListViews;
    • built-in animations include Alpha, SwingRightIn, SwingLeftIn, SwingBottomIn, SwingRightIn and ScaleIn;
    • other animations can easily be added;
    • supports StickyListHeaders; besides, you can add other implementations without any difficulties;
  • Swipe-to-Dismiss, Swipe-To-Dismiss with contextual undo;
  • Drag-and-Drop reordering;
  • an animated process of adding items;
  • you are able to smoothly expand your items to reveal more content.

3. AndroidImageSlider

AndroidImageSlider is an excellent example of an attractive, easy-to-use open source slideshow library. We believe it’s one of the most convenient image sliders on the Android platform.

With its help, you can easily upload your own images from an internet URL, drawable, or file and animate the slideshow with a range of different effects.

4. Transition Everywhere

Transition Everywhere is a backport of Transitions API for Android 4.0 and above. It allows you to change duration, interpolator and start delay for animators inside Transition. It has several transition types:

  • Slide;
  • Explode and Propagation;
  • ChangeImageTransfor;
  • Path motion;
  • TransitionName;
  • Scale;
  • Rotate.

The library can come in handy when you are going to animate changes to view position and size, extend Visibility class and perform fade in and fade out animations, or put the animations in sequential order.

5. Android Ripple Background

Android Ripple Background enables creating various ripple animation for your Android app. You can change their color, speed of the wave, and the number of ripples. It will be useful if you are going to animate a button click response or an incoming phone call, etc.

Читайте также:  Зеленый андроид с восклицательным знаком

6. Aphid FlipView

Aphid FlipView is a UI component to accomplish the flipping animation similar to Flipboard. It supports:

  • flipping horizontally;
  • an event listener to get notified when flipping finishes;
  • content reloading when flipping;
  • different bitmap format for animation, which can be used to reduce peak memory consumption.

7. FragmentTransactionExtended

FragmentTransactionExtended is a library equipped with a set of custom animations between fragments. Compared to FragmentTransaction, which accepts only simple animations, it got its list extended with more complex effects of the following animations:

8. KenBurnsView

KenBurnsView is a library that provides an extension to ImageView, which, in turn, creates an immersive experience by animating its drawable with the help of the Ken Burns Effect.

Advantages of the library are:

  • you can change the duration and the interpolator of transitions and pause/resume them.
  • you can define how the rectangles to be zoomed and panned will be generated;
  • it seamlessly works out of the box with your favorite image loader library;
  • you can start using it right away.

9. Reachability

Reachability is a library that enables easy accessing the top of the mobile phone screen. Animations implemented in iPhone 6 and iPhone 6 Plus inspired its developer. Here you can move either the screen or the hover.

10. AnimationEasingFunctions

AnimationEasingFunctions library was created based on AndroidViewAnimation with the help of Easing Functions. It is also aimed at facilitating the process of animation and making animations more real. You can implement it as a grade or just like a glider.

11. EasyAndroidAnimarions

EasyAndroidAnimations is another Android library that makes animation easier. It has above 50 built-in animations that will help you to implement many effects in your app with only several lines of code. You can include the library directly in your Gradle project.

12. InterfaceInteraction

InterfaceInteraction development was bolstered by the PhysicsLayout project. The library captures any interface (screen or view) and throws its UI elements over under the influence of gravity. As a result, one can move them from sideways obliquely. The gravity effect relies on the device’s accelerometer data. The stop method returns all UI elements back in place.

Another feature is a shake animation for UI elements.

The effects can easily be used to decorate any application.

13. ViewRevealAnimator

ViewRevealAnimator view with a lollipop style reveals effect. It enables you to create a smooth animated transition between items.

14. ArcAnimator

ArcAnimator is a library that helps create arc transition animation for Android 2.3. and above.

15. SearchMenuAnim

SearchMenuAnim allows creating a clear and effortless transition from a search icon to a search field.

16. Cross View

Cross View animates across in your app. The library enables you to define color and set a state directly. You can also set an animation duration in milliseconds.

17. WoWoViewPager

WoWoViewPager combines ViewPager and Animations to provide a simple way to create guide pages of the app. It supports some simple animations, namely:

  • translation;
  • scale;
  • alpha;
  • background color animations;
  • gif-playing;
  • SVG-drawing;
  • path-drawing.

18. Lottie

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.

By its means, designers can create and ship beautiful animations without an engineer painstakingly recreating it by hand.

Lottie’s major advantage is the support of a great variety of After Effects features.

19. FerrisWheelView

FerrisWheelView is a library that allows implementing an animated Ferris Wheel.

To sum up

Depending on the situation, it is easier to create some animations with the help of the existing libraries, but whereas your idea has a lot of specific details, you will need a custom solution.

Those above will definitely favor the development process of your app, reducing financial and time inputs.

Nevertheless, you should always bear in mind that:

  • animations should be functional, improving the user experience;
  • only appropriate elements should be animated. Animating every detail makes no sense. Besides, implementing resource-intensive elements would decrease your app performance and affect interaction with the user;
  • Render animations if you have such an opportunity, it will play into your hands as well.

Источник

Оцените статью