SlideShare a Scribd company logo
Animations
Android
Константин Золотов
План
Animation Frameworks (Drawable Animations, View Animations, Propertry Animations)
Layout Transitions (Layout Animations, Transitions Framework)
Window Transitions (Custom Animations, Shared Elements)
Moar (Ripples, Reveals, Links)
Animation Frameworks
Drawable Animations - покадровая анимация
View Animations - анимация отображения view
Property Animations - изменение свойств
Drawable Animations
Разметка:
1 <animation-list xmlns:android="http://schemas.android.com/apk/res/android">
2 <item android:drawable="@drawable/smile1" android:duration="200"/>
3 <item android:drawable="@drawable/smile2" android:duration="200"/>
4 <item android:drawable="@drawable/smile3" android:duration="200"/>
5 </animation-list>
Код:
1 AnimationDrawable mAnimation = new AnimationDrawable();
2 // устанавливаем циклическое повторение анимации
3 mAnimation.setOneShot(false);
4 mAnimation.addFrame(smile1, 250);
5 mAnimation.addFrame(smile1, 250);
6
7 AnimationDrawable animation = (AnimationDrawable)image.getBackground();
8 animation.start()
+/- Drawable Animations
сложные анимации
сложно создавать и поддерживать
много ресурсов -> долгие билды, больший вес выходного файла
View Animations
1 <?xml version="1.0" encoding="utf-8"?>
2 <set xmlns:android="http://schemas.android.com/apk/res/android"
3 android:fillAfter="true" >
4 <alpha
5 android:duration="1000"
6 android:fromAlpha="1.0"
7 android:interpolator="@android:anim/accelerate_interpolator"
8 android:toAlpha="0.0" />
9 </set>
Animation anim = AnimationUtils.loadAnimation(this, R.anim.test);
view.startAnimation(anim);
Чем плоха система
анимировать можно только Views
только простейшие преобразования (alpha, translate, scale, rotate)
объект анимации остается неизменным
Property Animations
1 ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);
2 animation.setDuration(1000);
3 animation.start();
4
5 ObjectAnimator anim = ObjectAnimator.ofFloat(shape, "translationX",300);
6 anim.start();
Интерполяторы
Change Fragment animation
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
1 <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
2 android:interpolator="@android:interpolator/accelerate_quad"
3 android:valueFrom="0"
4 android:valueTo="1"
5 android:propertyName="alpha"
6 android:duration="@android:integer/config_mediumAnimTime" />
Animating Layout Changes
1 <LinearLayout android:id="@+id/container"
2 android:animateLayoutChanges="true"
3 ...
4 />
Transitions Framework
Создание сцен
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:id="@+id/master_layout">
3 <TextView
4 android:id="@+id/title"
5 ...
6 android:text="Title"/>
7 <FrameLayout
8 android:id="@+id/scene_root">
9 <include layout="@layout/a_scene" />
10 </FrameLayout>
11 </LinearLayout>
mSceneRoot = (ViewGroup) ndViewById(R.id.scene_root);
Создание сцен
сцена 1
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:id="@+id/scene_container"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" >
5 <View
6 android:width="10dp"
7 android:height="10dp"
8 android:id="@+id/view1 />
9 </RelativeLayout>
сцена 2
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:id="@+id/scene_container"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" >
5 android:width="100dp"
6 android:height="100dp"
7 android:id="@+id/view1 />
Создание сцены из Layout
1 Scene mAScene;
2 Scene mAnotherScene;
3
4 // Create the scenes
5 mAScene = Scene.getSceneForLayout(mSceneRoot, R.layout.a_scene, this);
6 mAnotherScene =
7 Scene.getSceneForLayout(mSceneRoot, R.layout.another_scene, this);
Создание Transition
1. Добавить директорию res/transition/
2. Добавить xml файл (res/transition/fade_transition.xml)
<fade xmlns:android="http://schemas.android.com/apk/res/android" />
Transition mFadeTransition = TransitionInflater.from(this).
inflateTransition(R.transition.fade_transition);
3. Создать из кода Transition mFadeTransition = new Fade();
Использование Transition
1. Сцены
TransitionManager.go(mEndingScene, mFadeTransition);
1. Вне сцен
TransitionManager.beginDelayedTransition(mRootView, mFade); mRootView.addView(mLabelText);
Shared element
1 final View imgContainerView = findViewById(R.id.img_container);
2
3 // get the common element for the transition in this activity
4 final View androidRobotView = findViewById(R.id.image_small);
5
6 // define a click listener
7 imgContainerView.setOnClickListener(new View.OnClickListener() {
8 @Override
9 public void onClick(View view) {
10 Intent intent = new Intent(this, Activity2.class);
11 // create the transition animation - the images in the layouts
12 // of both activities are defined with android:transitionName="robot"
13 ActivityOptions options = ActivityOptions
14 .makeSceneTransitionAnimation(this, androidRobotView, "robot");
15 // start the new activity
16 startActivity(intent, options.toBundle());
17 }
18 });
Animate View State Changes
1 <selector xmlns:android="http://schemas.android.com/apk/res/android">
2 <item android:state_pressed="true">
3 <set>
4 <objectAnimator android:propertyName="translationZ"
5 android:duration="@android:integer/config_shortAnimTime"
6 android:valueTo="2dp"
7 android:valueType="floatType"/>
8 </set>
9 </item>
10 <item android:state_enabled="true"
11 android:state_pressed="false"
12 android:state_focused="true">
13 <set>
14 <objectAnimator android:propertyName="translationZ"
15 android:duration="100"
16 android:valueTo="0"
17 android:valueType="floatType"/>
18 </set>
19 </item>
20 </selector>
Ripples
1 <selector xmlns:android="http://schemas.android.com/apk/res/android">
2 <item android:state_selected="true"
android:drawable="@drawable/circular_button_selected"/>
3 <item android:drawable="@drawable/circular_button"/>
4 </selector>
5
6 <ripple android:color="#ffff0000">
7 </ripple>
Circular Reveal
1 int finalRadius = Math.hypot(myView.getWidth(), myView.getHeight());
2
3 // create the animator for this view (the start radius is zero)
4 Animator anim =
5 ViewAnimationUtils.createCircularReveal(myView, 0, 0, 0, finalRadius);
6 anim.start();
Полезные ссылки
View animation
View animation examples
Material animations
Shared Element Activity Transition
Transitions
Android arsenal

More Related Content

PDF
Seminar: Эффективное использование среды разработки и компилятора C++
PDF
PDF
Работа с графической подсистемой (Lecture 10 – Graphics)
PDF
Database (Lecture 14 – database)
PDF
Android - 05 - Android basics
PDF
Работа с соцсетями (Lecture 19 – social)
PDF
Webinar: Возможности RAD Studio 10 Seattle для разработки Windows 10 приложений
PPTX
Ссылки, списки и меню (HTML5 тема 06 - ссылки, списки и меню)
Seminar: Эффективное использование среды разработки и компилятора C++
Работа с графической подсистемой (Lecture 10 – Graphics)
Database (Lecture 14 – database)
Android - 05 - Android basics
Работа с соцсетями (Lecture 19 – social)
Webinar: Возможности RAD Studio 10 Seattle для разработки Windows 10 приложений
Ссылки, списки и меню (HTML5 тема 06 - ссылки, списки и меню)

Viewers also liked (19)

PPTX
Семантика текста (HTML5 тема 04 - семантика текста)
PPTX
DIOR-DNA, Anton Zvonov, Part 1, Activities (жизненный цикл)
PDF
Введение в Android-разработку (Lecture 06 – basics)
PPTX
Стилизация текста (HTML5 тема 05 - стилизация текста)
PDF
Webinar: Использование UWP/WinRT Contracts и Notification в Windows 10
PDF
PDF
PDF
Системы автоматизированной сборки (Lecture 05 – gradle)
PDF
PDF
Fragments (Lecture 09 – Fragments)
PDF
PDF
Toolbar (Lecture 16 – toolbar)
PDF
Webinar: Разработка мобильного приложения для заучивания стихов в Delphi
PDF
Seminar: Установка и настройка рабочего стенда разработчика Android-приложени...
PDF
Push Notifications (Lecture 22 – push notifications)
PDF
Библиотеки для передачи данных (Lecture 13 – multithreading, network (libs))
PDF
Android - 10 - Graphics
PPTX
Views обзор
Семантика текста (HTML5 тема 04 - семантика текста)
DIOR-DNA, Anton Zvonov, Part 1, Activities (жизненный цикл)
Введение в Android-разработку (Lecture 06 – basics)
Стилизация текста (HTML5 тема 05 - стилизация текста)
Webinar: Использование UWP/WinRT Contracts и Notification в Windows 10
Системы автоматизированной сборки (Lecture 05 – gradle)
Fragments (Lecture 09 – Fragments)
Toolbar (Lecture 16 – toolbar)
Webinar: Разработка мобильного приложения для заучивания стихов в Delphi
Seminar: Установка и настройка рабочего стенда разработчика Android-приложени...
Push Notifications (Lecture 22 – push notifications)
Библиотеки для передачи данных (Lecture 13 – multithreading, network (libs))
Android - 10 - Graphics
Views обзор
Ad

Similar to Animations (Lecture 17 – animations) (20)

PDF
2014-08-02 03 Дмитрий Шматко. Первые впечатления от Node.js
PPTX
Антон Валюх - Использование паттерна Mvvm в android
PPTX
Создание графического интерфейса пользователя мобильных Android приложений (ч...
PDF
Android Transition - плавные переходы на Android
PDF
Frontend весна 2014 лекция 1
PDF
Автоматизация UI тестирования под Windows и Windows Phone
PPT
Selenium 2.0: обзор новых возможностей
PDF
"Адаптивный дизайн интерфейса JS API Яндекс.Карт и особенности его реализации...
PDF
Фреймворк Slot, Good Parts, Александр Бирюков
PDF
Артём Поликарпов - Фоторама - простая и мощная галерея на JS | Happydev'12
PDF
Не JS во фронтенде
PPTX
iOS and Android Mobile Test Automation
PPT
Вебинар "Оптимизация производительности мобильных веб-приложений"
PDF
Mobile automation uamobile
PDF
Превышаем скоростные лимиты с Angular 2
PDF
Превышаем скоростные лимиты с Angular 2 / Алексей Охрименко (IPONWEB)
PPT
Lviv MDDay 2014. Олександр Зозуля “Google карти для android”
PDF
Принципы разработки ПО для iPhone с использованием акселерометра
PPTX
Enterprise flex pure mvc, slides, russian
2014-08-02 03 Дмитрий Шматко. Первые впечатления от Node.js
Антон Валюх - Использование паттерна Mvvm в android
Создание графического интерфейса пользователя мобильных Android приложений (ч...
Android Transition - плавные переходы на Android
Frontend весна 2014 лекция 1
Автоматизация UI тестирования под Windows и Windows Phone
Selenium 2.0: обзор новых возможностей
"Адаптивный дизайн интерфейса JS API Яндекс.Карт и особенности его реализации...
Фреймворк Slot, Good Parts, Александр Бирюков
Артём Поликарпов - Фоторама - простая и мощная галерея на JS | Happydev'12
Не JS во фронтенде
iOS and Android Mobile Test Automation
Вебинар "Оптимизация производительности мобильных веб-приложений"
Mobile automation uamobile
Превышаем скоростные лимиты с Angular 2
Превышаем скоростные лимиты с Angular 2 / Алексей Охрименко (IPONWEB)
Lviv MDDay 2014. Олександр Зозуля “Google карти для android”
Принципы разработки ПО для iPhone с использованием акселерометра
Enterprise flex pure mvc, slides, russian
Ad

More from Noveo (18)

PPTX
Гуманитарные специальности в IT-индустрии
PPTX
Box model, display and position (HTML5 тема 07 - box model, display position)
PPTX
Основы CSS (HTML5 тема 02 - основы CSS)
PPTX
Структура HTML документа (HTML5 тема 01 - структура html документа)
PPTX
Yii2
PPTX
Сессии и авторизация
PPTX
Rest
PPTX
PHP basic
PPTX
PHP Advanced
PPTX
PHP and MySQL
PPTX
MySQL
PDF
RxJava+RxAndroid (Lecture 20 – rx java)
PDF
Работа с геоданными (Lecture 18 – geolocation)
PDF
Material Design (Lecture 15 – material design)
PDF
Многопоточность, работа с сетью (Lecture 12 – multithreading, network)
PDF
XML, JSON (Lecture 11 – XML, JSON)
PDF
Android - 16 - QR
PDF
03 коллекции
Гуманитарные специальности в IT-индустрии
Box model, display and position (HTML5 тема 07 - box model, display position)
Основы CSS (HTML5 тема 02 - основы CSS)
Структура HTML документа (HTML5 тема 01 - структура html документа)
Yii2
Сессии и авторизация
Rest
PHP basic
PHP Advanced
PHP and MySQL
MySQL
RxJava+RxAndroid (Lecture 20 – rx java)
Работа с геоданными (Lecture 18 – geolocation)
Material Design (Lecture 15 – material design)
Многопоточность, работа с сетью (Lecture 12 – multithreading, network)
XML, JSON (Lecture 11 – XML, JSON)
Android - 16 - QR
03 коллекции

Animations (Lecture 17 – animations)

  • 2. План Animation Frameworks (Drawable Animations, View Animations, Propertry Animations) Layout Transitions (Layout Animations, Transitions Framework) Window Transitions (Custom Animations, Shared Elements) Moar (Ripples, Reveals, Links)
  • 3. Animation Frameworks Drawable Animations - покадровая анимация View Animations - анимация отображения view Property Animations - изменение свойств
  • 4. Drawable Animations Разметка: 1 <animation-list xmlns:android="http://schemas.android.com/apk/res/android"> 2 <item android:drawable="@drawable/smile1" android:duration="200"/> 3 <item android:drawable="@drawable/smile2" android:duration="200"/> 4 <item android:drawable="@drawable/smile3" android:duration="200"/> 5 </animation-list> Код: 1 AnimationDrawable mAnimation = new AnimationDrawable(); 2 // устанавливаем циклическое повторение анимации 3 mAnimation.setOneShot(false); 4 mAnimation.addFrame(smile1, 250); 5 mAnimation.addFrame(smile1, 250); 6 7 AnimationDrawable animation = (AnimationDrawable)image.getBackground(); 8 animation.start()
  • 5. +/- Drawable Animations сложные анимации сложно создавать и поддерживать много ресурсов -> долгие билды, больший вес выходного файла
  • 6. View Animations 1 <?xml version="1.0" encoding="utf-8"?> 2 <set xmlns:android="http://schemas.android.com/apk/res/android" 3 android:fillAfter="true" > 4 <alpha 5 android:duration="1000" 6 android:fromAlpha="1.0" 7 android:interpolator="@android:anim/accelerate_interpolator" 8 android:toAlpha="0.0" /> 9 </set> Animation anim = AnimationUtils.loadAnimation(this, R.anim.test); view.startAnimation(anim);
  • 7. Чем плоха система анимировать можно только Views только простейшие преобразования (alpha, translate, scale, rotate) объект анимации остается неизменным
  • 8. Property Animations 1 ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f); 2 animation.setDuration(1000); 3 animation.start(); 4 5 ObjectAnimator anim = ObjectAnimator.ofFloat(shape, "translationX",300); 6 anim.start();
  • 10. Change Fragment animation ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); 1 <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" 2 android:interpolator="@android:interpolator/accelerate_quad" 3 android:valueFrom="0" 4 android:valueTo="1" 5 android:propertyName="alpha" 6 android:duration="@android:integer/config_mediumAnimTime" />
  • 11. Animating Layout Changes 1 <LinearLayout android:id="@+id/container" 2 android:animateLayoutChanges="true" 3 ... 4 />
  • 13. Создание сцен 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/master_layout"> 3 <TextView 4 android:id="@+id/title" 5 ... 6 android:text="Title"/> 7 <FrameLayout 8 android:id="@+id/scene_root"> 9 <include layout="@layout/a_scene" /> 10 </FrameLayout> 11 </LinearLayout> mSceneRoot = (ViewGroup) ndViewById(R.id.scene_root);
  • 14. Создание сцен сцена 1 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/scene_container" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" > 5 <View 6 android:width="10dp" 7 android:height="10dp" 8 android:id="@+id/view1 /> 9 </RelativeLayout> сцена 2 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/scene_container" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" > 5 android:width="100dp" 6 android:height="100dp" 7 android:id="@+id/view1 />
  • 15. Создание сцены из Layout 1 Scene mAScene; 2 Scene mAnotherScene; 3 4 // Create the scenes 5 mAScene = Scene.getSceneForLayout(mSceneRoot, R.layout.a_scene, this); 6 mAnotherScene = 7 Scene.getSceneForLayout(mSceneRoot, R.layout.another_scene, this);
  • 16. Создание Transition 1. Добавить директорию res/transition/ 2. Добавить xml файл (res/transition/fade_transition.xml) <fade xmlns:android="http://schemas.android.com/apk/res/android" /> Transition mFadeTransition = TransitionInflater.from(this). inflateTransition(R.transition.fade_transition); 3. Создать из кода Transition mFadeTransition = new Fade();
  • 17. Использование Transition 1. Сцены TransitionManager.go(mEndingScene, mFadeTransition); 1. Вне сцен TransitionManager.beginDelayedTransition(mRootView, mFade); mRootView.addView(mLabelText);
  • 18. Shared element 1 final View imgContainerView = findViewById(R.id.img_container); 2 3 // get the common element for the transition in this activity 4 final View androidRobotView = findViewById(R.id.image_small); 5 6 // define a click listener 7 imgContainerView.setOnClickListener(new View.OnClickListener() { 8 @Override 9 public void onClick(View view) { 10 Intent intent = new Intent(this, Activity2.class); 11 // create the transition animation - the images in the layouts 12 // of both activities are defined with android:transitionName="robot" 13 ActivityOptions options = ActivityOptions 14 .makeSceneTransitionAnimation(this, androidRobotView, "robot"); 15 // start the new activity 16 startActivity(intent, options.toBundle()); 17 } 18 });
  • 19. Animate View State Changes 1 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 2 <item android:state_pressed="true"> 3 <set> 4 <objectAnimator android:propertyName="translationZ" 5 android:duration="@android:integer/config_shortAnimTime" 6 android:valueTo="2dp" 7 android:valueType="floatType"/> 8 </set> 9 </item> 10 <item android:state_enabled="true" 11 android:state_pressed="false" 12 android:state_focused="true"> 13 <set> 14 <objectAnimator android:propertyName="translationZ" 15 android:duration="100" 16 android:valueTo="0" 17 android:valueType="floatType"/> 18 </set> 19 </item> 20 </selector>
  • 20. Ripples 1 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 2 <item android:state_selected="true" android:drawable="@drawable/circular_button_selected"/> 3 <item android:drawable="@drawable/circular_button"/> 4 </selector> 5 6 <ripple android:color="#ffff0000"> 7 </ripple>
  • 21. Circular Reveal 1 int finalRadius = Math.hypot(myView.getWidth(), myView.getHeight()); 2 3 // create the animator for this view (the start radius is zero) 4 Animator anim = 5 ViewAnimationUtils.createCircularReveal(myView, 0, 0, 0, finalRadius); 6 anim.start();
  • 22. Полезные ссылки View animation View animation examples Material animations Shared Element Activity Transition Transitions Android arsenal