How to make animations in android

Using animations in Android application — Tutorial

Android Property Animation API. This tutorial describes how to use the animation API in Android.

1. Android Animations

1.1. Using animations

Android allows changing object properties over a certain time interval via the properties animation API.

The superclass of the animation API is the Animator class. The ObjectAnimator class can be used to modify attributes of an object.

You can also add an AnimatorListener class to your Animator class. This listener is called in the different phases of the animation. You can use this listener to perform actions before or after a certain animation, e.g. add or remove a View from a ViewGroup .

The animate() method on a View object returns an ViewPropertyAnimator object for the view. It provides a fluent API to typical animations which can be performed on views.

The following code shows an example.

You can also register action, which are executed before the start or after the end of the animation.

1.2. Define the rate of change for an animation

Via the setInterpolator() method you register an TimeInterpolator object with an animation. It defines the rate of change for an animation.

The standard is linear. The Android platform defines a few default ones. For example, the AccelerateDecelerateInterpolator class defines that the animation starts and ends slowly but accelerates through the middle.

1.3. Using animations with arbitrary properties

The animation system cannot automatically understand every type. Via the setEvaluator method you can set an object of type TypeEvaluator . It allows creating animations for arbitrary types, by providing custom evaluators for these types.

1.4. Layout animations

The LayoutTransition class allows setting animations on a layout container and a change on the view hierarchy of this container will be animated.

1.5. Animations for Activity transition

Animations can be applied to Views but it is also possible to apply them on the transition between activities.

The ActivityOptions class allows defining defaults or customer animations.

2. Android Basics

The following description assumes that you have already basic knowledge in Android development.

Please check https://www.vogella.com/tutorials/Android/article.html — Android development tutorial, to learn the basics. Also see https://www.vogella.com/android.html — Android development tutorials, for more information about Android development.

3. Exercise: Using the properties animations API

This exercise demonstrates the usage of the Properties animation API.

Create a new Android project with the top level package name com.vogella.android.animation.views and an activity called AnimationExampleActivity. The layout file should be called activity_main.xml.

Change your layout file to the following code.

Create the following menu resource.

Читайте также:  Брокен сворд для андроид

Change your activity similar to the following listing.

Create a new xml layout file called target like the following.

Create a new HitActivity activity.

If you run this example and press the different buttons, the animation should start. Via the toolbar, you can start your HitActivity .

4. Activity animations in Android with shared views

Android 5.0 adds the capability to animate between activities and to have shared views between these activity. If you define a shared part the old view with be animating into the position and size of the new view.

To test this create a project with the top level package called com.vogella.android.activityanimationwithsharedviews .

Create two activity with two different layout, both containing a ImageView with the same android:transitionName property.

Источник

Анимации в Android по полочкам (Часть 3. «Низкоуровневые» анимации)

Все методы рассмотренные в предыдущих частях хороши и удобны, однако если нам нужно анимировать большое количество объектов, они могут оказаться не подходящими. В данной части мы рассмотрим способы которые нам позволят работать с действительно большим количеством объектов и создавать программно сложные анимации.

Часть 3. «Низкоуровневые» анимации

1. Рисование на канвасе View

Первый способ который мы рассмотрим это рисование в методе onDraw нашего объекта View . Реализуется данный способ просто, достаточно переопределить onDraw и в конце вызвать postInvalidateOnAnimation() .

В данном примере наш drawable будет перемещаться по оси x.

Пример со снежинками выше будет занимать несколько больше кода, т.к. нам нужно хранить состояние каждой отдельной снежинки отдельно.

  • Случаи в которых легче нарисовать анимацию программно

Достоинства:

  • Можно создавать анимации зависящие абсолютно от любых параметров
  • Нет лишних затрат на объекты View

Недостатки:

  • Расчёты анимации и отрисовка происходят в UI thread

2. Рисование на канвасе SurfaceView

Что если расчёт следующего шага анимации будет занимать значительное время? Мы всё ещё можем воспользоваться первым способом и вынести расчёты в отдельный поток. Но это всё равно не приведёт к 100% плавности в анимации т.к. UI thread может быть загружен ещё чем либо помимо нашей анимации.

Android позволяет отвязаться от основного цикла(main loop) отрисовки с помощью компонента SurfaceView . А раз мы больше не привязаны к основному циклу, то нам придётся держать свой поток для расчётов и отрисовки. SurfaceView предоставляет коллбэки в которых мы можем запустить и остановить наш поток. В потоке по окончанию расчётов мы будем отрисовывать нашу анимацию.

Реализация той же анимации снежинок будет выглядеть следующим образом:

  • Случаи в которых легче нарисовать анимацию программно
  • Игры

Достоинства:

  • Можно создавать анимации зависящие абсолютно от любых параметров
  • Нет лишних затрат на объекты View

Недостатки:

3. OpenGL


Точно также, как и на канвасе, мы можем рисовать используя OpenGL API. Если вы задумали что-либо сложнее чем куб на картинке, то стоит посмотреть в сторону какого-либо движка, например libgdx. К сожалению, даже базовый пример займёт здесь довольно много места, поэтому ограничимся только этим кратким превью.

  • Высокая производительность и управление памятью, шейдеры

Недостатки:

Источник

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.
Читайте также:  Total commander mod menu android

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.

Источник

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