What is window animation in android

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

Приведённые в предыдущей части инструменты были относительно низкоуровневыми и в Android есть куда более простые способы добиться красивых анимаций не прибегая к прямому рисованию графики или изменению свойств объектов.

В этой части мы рассмотрим как можно минимумом усилий получить красивые анимации.

Часть 2. Комплексные анимации

1. Анимация изменений лэйаута (aka animateLayoutChanges)

Всё, что нам нужно сделать, чтобы добиться анимации как на гифке выше — это добавить флаг animateLayoutChanges в наш ViewGroup в xml. Теперь, когда мы удаляем или добавляем элемент в наш контейнер, либо изменяем его свойства, они автоматически будут анимированы.

Ладно, я немного слукавил когда говорил, что чтобы получить анимацию как на гифке выше, нужно всего лишь установить флаг. Добавление animateLayoutChanges на самом деле устанавливает LayoutTransition нашей ViewGroup. Но LayoutTransition по умолчанию анимирует только изменение видимости объектов в лэйауте. Поэтому если мы хотим изменять свойства объекта (например ширину и высоту) нужно включить эту опцию отдельно:

Теперь точно всё. Если захочется как-то кастомизировать это поведение, то у LayoutTransition есть метод setAnimator позволяющий задать свою собственную анимацию изменений. Ну самые хардкорные ребята всегда могут написать свой LayoutTransition .

• Применение:
Базовая анимация изменений объектов на сцене.
• Достоинства:
Минимальные трудозатраты
• Недостатки:
Слабая кастомизация

2. Transitions framework

Начиная с API 19 в Android появился новый фреймворк позволяющий создавать сложные анимации с участием большого количества элементов и минимумом кода.

Есть два основных варианта его использования:

1) Использование TransitionManager.beginDelayedTransition(ViewGroup)
Чтобы создать анимацию необходимо перед внесением изменений в наши View вызвать TransitionManager.beginDelayedTransition(ViewGroup) и передать в него ViewGroup, который мы хотим анимировать. Фрэймворк запомнит состояние View и запустит анимацию на следующем кадре.

2) Создание сцен
Создание анимации в этом случае сводится к созданию двух похожих xml, отвечающих за начальное и конечное состояние ваших анимаций. Соответственно, id объектов в xml должны совпадать, чтобы дать фреймворку возможность найти соответствие (На самом деле beginDelayedTransition тоже создаёт сцены, одну в момент вызова, а вторую на следующем кадре. После чего запускает анимацию между ними).

Кастомизация в Transitions framework достигается за счёт передачи объекта Transition вторым параметром. По умолчанию используется AutoTransition() , так что код ниже будет работать абсолютно так-же, как и код выше.

И если заглянуть внутрь AutoTransition можно заметить что анимации будут происходить в последовательно в следующем порядке:
— анимируются исчезающие объекты
— анимируются изменения размеров
— анимируются появляющиеся объекты

• Применение:
Анимация большого количества объектов

• Достоинства:
Минимальные трудозатраты
Доступная кастомизация

Источник

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

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

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

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

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

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

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

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

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

Читайте также:  Android studio arraylist get

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

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

Большое потребление ресурсов и, как следствие, довольно затратный импорт в приложение с возможностью получить 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 вручную можно воспользоваться онлайн инструментом.

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

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

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

Источник

Simple Animations in Android

Dec 14, 2018 · 9 min read

Animations in Android are a cool way to make your UI stand out and are also useful to notify users when the UI changes state. There are many different types of animations and can get very complicated, that is why this blog post is to help you start out with simple animations.

Android supports animations for both views and transitions between activities, however, the addition of transitions between activities is fairly new. There are three animation systems that work differently for different cases:

  1. Property Animations — This most popular type of animation, introduced in Android 3.0, is used to change the properties of an object. If you want to handle animation when you click a view, use Property Animations as they change the state as well as behavior.
  2. View Animations — Used to do simple animations like changing size, position, and rotation. They are easy to build but are slower and less flexible than Property Animations. The problem with View Animations is that, though the View state changes, its property still remains at the original position. Due to this, View Animations have been used less often since Property Animations were introduced.
  3. Transition Animations — This animation is the latest addition being introduced to Android 4.0 devices. The Transitions API framework enables layout changes within an activity. There are Transitions of a view, an Activity or a Fragment. Activity Transitions animates the transition as an activity enters the screen when an Intent is executed while Fragment Transitions animates the transition as a fragment enters or exits the screen when a transaction occurs.
Читайте также:  Живые обои для андроид кошек

Powered by these a nimation frameworks, there are two other types of animations that are lesser known and used:

  1. Layout Animations — This type of animation enables us to do animations on a ViewGroup such as a LinearLayout, a RelativeLayout or a ListView. Using the Transitions API, the animations to the view changes can be specified. For lower versions, layout animations can still be enabled, but there is no way to dictate how the transitions occur.
  2. Drawable Animations — Used to animate by displaying drawables in quick succession.

Property Animations

The primary motivation for the introduction of Property Animations was that before there could only be animations of Views with buttons, TextViews, LinearLayout etc. and you could only move, rotate, scale and fade a View. Thus, being able to animate properties of objects other than a View is what Property Animations do.

The table below shows the properties commonly animated on views in Property Animations:

The animation in Property Animations is done by ValueAnimator. This class keeps track of animation duration and start and end values of the property that it is animating. The image below shows the UML diagram of how this class interacts:

As seen above in the diagram, A ValueAnimator as two important properties TimeInterpolator and TypeEvaluator. A TimeInterpolater keeps track of the rate of change of an animation which allows animations to have non-linear motion. The different types of interpolators are:

  • Accelerate Decelerate — The rate of change starts and ends slowly but accelerates through the middle.
  • Accelerate — The rate of change starts out slowly and then accelerates.
  • Anticipate — The change starts backward then flings forwards.
  • Anticipate Overshoot — The change starts backward then flings forward and overshoots the target value and finally goes back to the final value.
  • Bounce — The change bounces at the end.
  • Decelerate — The rate of change starts out quickly and then decelerates.
  • Fast Out Linear In — Corresponding to fast_out_linear_in in R.interpolator.
  • Fast Out Slow In — Corresponding to fast_out_slow_in in R.interpolator.
  • Linear — The rate of change is constant.
  • Linear Out Slow In — Corresponding to linear_out_slow_in in R.interpolator.
  • Overshoot — The change flings forward and overshoots the last value then comes back.

A TypeEvaluator is an interface that allows the creation of animations on arbitrary property types such as int, float, rgb, etc. or use a custom TypeEvaluator.

Animations Using ValueAnimator

ValueAnimator allows the developer to have more control over animations and customize them at each step of execution. In order to initiate ValueAnimator, you will need to call one of these methods: ofInt(), ofFloat(), or ofObject(). For example:

You can then change the state of the view by setting the duration, repeats, interpolator and other properties mentioned above which can be seen in the code below:

The same thing can be achieved using a resource file, in /res/animator/valueanimator, shown below:

You would then write in the Activity you want to animate:

Animations Using ObjectAnimator

The ObjectAnimator is a subclass of ValueAnimator and provides support for animating properties on target objects. The constructors of the ObjectAnimator take the object that is targeted that will be animated. It also takes in the name of the property that you want to perform on the object. Set and get methods can also be used to further animate the object and the animation will call these methods.

The code below shows an example of how an ObjectAnimator can be initialized and used to create a button that fades out when clicked on:

Properties supported by ObjectAnimation include ALPHA, ROTATION, ROTATION_X, SCLAE_X, SCALE_Y, TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z, X, Y, Z in order to improve performance on these animations. An example would be:

Using a different interpolator we can achieve this animation:

Читайте также:  Мой календарь андроид синхронизация google

which can be done by:

The same thing as above can be written using a resource file, /res/animator/objectanimator/, as shown:

Then in your activity, you would connect the resource file and the animation as shown:

Starting from API 23, it is possible to use PropertyValuesHolder and Keyframe in resource files to create more complex animations. PropertyValuesHolders allows animators to animate several properties in conjunction with one another. Using Keyframes allows animations to follow more complex paths from the start to the end values. In addition, an optional interpolator can be specified. The interpolator will be applied on the interval between the keyframe that the interpolator is set on and the previous keyframe. When no interpolator is supplied, the default AccelerateDecelerateInterpolator, which increases the speed first and then decreases the speed, will be used.

Transitions

Transitions were introduced in Android KitKat with Scenes and Transitions APIs. This is all done with the Transition API which holds information about animations that will be run on its targets during a scene change. A Scene is the state of all views in the layout container. A Transition is the set of Animators that is applied to views in your specified Scene in order to perform smooth transitions from one scene to another. Transitions between Activities and Fragments was introduced to Android 5.0, it is a fairly new concept so I will be focusing on simple transitions on views. The diagram below shows how the transition framework creates an animation.

It is important that your API is at version 19 or higher or the Transition API will not work.

Take for example we want to a text to appear when we click a button:

We are setting the visibility of the TextView to gone because we do not want to see the text until the button is clicked on. Then in your activity, you would include:

As we did with ViewAnimator and ObjectAnimator, we can change the duration (setDuration(int)), interpolator (setInterpolator(TimeInterpolator)), and delay(setStartDelway(int)) of the transition.

There is a new package that allows you to implement more transitions to your views that are not in the Transition API from android. This package is called transitioneverywhere which can be implemented by first putting the following code in your grade file:

Then in your activities that were using the Transitions API, import android.transition.*, you want to replace this import with import com.transitionseverywhere.*. Transitions that can be used in this new package are:

  • ChangeBounds — It animates changes to view position and size. In the example above, ChangeBounds moves the button depending on if the text is shown or not.
  • Fade — It extends Visibility class and performs fade in and fade out. In the example above, it is what makes the TextView visible and not visible.
  • TransitionSet — A Transition that is a set of another Transition. They can start together or sequentially, to change it call setOrdering().
  • AutoTransition — A subclass of TransitionSet that creates a default transition that automatically fades, moves and resizes your views during a scene change.
  • Slide — Like Fade transition, extends Visibility class. This allows a view during a scene slide in from one of the sides. For example, you can do Slide(Gravity.LEFT). This requires API 21 or higher to work. You would do to allow the text to slide from the left, assuming that your TextView visibility is initially set to gone:
  • ChangeImageTransform — This will animate an image for a situation when scaleType of an ImageView is changed. In most cases, it is paired with ChangeBounds to animate position, size, and scaleType of the image.
  • ChangeText — You can also change the text with a click of a button as shown below:

Summary

As seen animations in Android can be fairly easy and fun! This post only touches the surface of the possible animations and transitions that are possible in Android, however, this will allow you to start playing with animations. Look at the Android documentation on animations and the Transition API in order to do more complicated animations and even transitions between Activities.

Источник

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