Сегодня мы рассмотрим пример того, как происходит создание анимации на Андроид.
Андроид поддерживает два типа анимации: анимация преобразований (Tweened Animations) и анимация «кадр за кадором» (Frame-by-frame).
Анимация преобразований применяется к объектам типа View и позволяет изменять их размер, положение и прозрачность. Например, вы можете задать эффект затухания для представления (View) или повернуть его.
Покадровая анимация (frame-by-frame) показывает различные эффекты рисования в представлении. Этот тип анимации ограничен оригинальными размерами представления (View).
Анимация может быть применена не только к представлениям, но и при переходе от одного Activity к другому.
Для этого вы должны использовать метод overridePendingTransition() в текущем Activity.
Анимация преобразований — это экземпляр абстрактного класса Animation. Вы имеете предопределённые Java-классы: AlphaAnimation, RotateAnimation, ScaleAnimation и TranslateAnimation.
Анимация преобразований может быть применена к слою или напрямую к представлению. Если анимация применяется к слою, то она выполняется всякий раз, когда представление добавляется к слою или удаляется из него. Если анимация применяется к представлению, то вы должны явно стартовать её начало из кода. Если вы применяете анимацию к слою, то используйте класс «LayoutAnimationController».
Также можно использовать групповую анимацию, использовав класс «AnimationSet», в котором нужно задать время старта, длительность и размер смещения.
Начало анимации задаётся с помощью метода view.startAnimation(), принимает в качестве параметра AnimationSet. По умолчанию AnimationSet будет запущен один раз, изменить такое поведение можно с помощью методов setRepeatModel() и setRepeastCount(). После завершения анимации преобразований представления возвращаются в изначальное положение. Изменить такое поведение можно в обработчике «Animation.AnimationListener». Он сигнализирует о моменте начала и конца анимации. В нём вы можете изменить окончательный вид представления, например сделать невидимым объект после плавного затухания.
Анимация может задаваться в виде XML-файла в ресурсах. В таком случае файл должен располагаться в каталоге «res/anim». Загружать такой ресурс надо таким образом: AnimationUtils.loadAnimiation(this,R.anim.Animation).
Скорость анимации можно задать в классе «Interpolator». Так же существуют и другие классы: AccelerateInterpolator, DecelerateInterpolator, LinearInterpolator, BounceInterpolator, OvershootInterpolator и CycleInterpolator. К примеру, BounceInterpolator используется для эффекта колебания. Подробнее о классах Interpolator можно узнать в документации.
Мы создадим приложение для Android, которое проиллюстрирует различные типы анимации.
1. Создайте Android-проект «AnimationSample.com.com» с Activity «AnimationSample». Измените файл «main.xml» чтобы он выглядел таким вот образом:
1 2 3 4 5 6 7 8 | <!--?xml version="1.0" encoding="utf-8"?--> <button></button> <button></button> <button></button> <button></button> |
<!--?xml version="1.0" encoding="utf-8"?--> <button></button> <button></button> <button></button> <button></button>
2. Опишите вашу анимацию в файле «myanimation.xml»:
1 | <!--?xml version="1.0" encoding="utf-8"?--> |
<!--?xml version="1.0" encoding="utf-8"?-->
3. Измените код для вашего Activity:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | package animationsample.com.com; import android.R.layout; import android.app.Activity; import android.graphics.Paint; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.animation.BounceInterpolator; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.TextView; import android.widget.Toast; public class AnimationSampleActivity extends Activity implements AnimationListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startAnimation(View view) { switch (view.getId()) { case R.id.Button01: //загружаем описание анимации из XML-файла Animation animation1 = AnimationUtils.loadAnimation(this, R.anim.myanimation); animation1.setAnimationListener(this); View animatedView1 = findViewById(R.id.rotatetext); animatedView1.startAnimation(animation1); break; case R.id.Button02: //показывает как объявить анимацию из кода //используется Interpolator (BounceInterpolator) Paint paint = new Paint(); TextView animatedView2 = (TextView) findViewById(R.id.scrolltext); float measureTextCenter = paint.measureText(animatedView2.getText().toString()); Animation animation2 = new TranslateAnimation(0f,-measureTextCenter,0.0f,0.0f); animation2.setDuration(5000); animation2.setInterpolator(new BounceInterpolator()); animatedView2.startAnimation(animation2); break; case R.id.Button03: //демонстрация эффекта затухания и добавление AnimationListener // TextView animatedView3 = (TextView) findViewById(R.id.fadeout); float from = 1.0f; float to = 0.0f; if (animatedView3.getVisibility()==View.INVISIBLE) { from = to; to = 1.0f; } Animation animation3 = new AlphaAnimation(from,to); animation3.setDuration(5000); animation3.setAnimationListener(this); animatedView3.startAnimation(animation3); break; case R.id.Button04: //демонстрация LayoutAnimation ViewGroup layout = (ViewGroup) findViewById(R.id.layout); Animation animation4 = new AlphaAnimation(0.0f, 1.0f); animation4.setDuration(5000); LayoutAnimationController controller = new LayoutAnimationController(animation4,0); layout.setLayoutAnimation(controller); View button = findViewById(R.id.Button03); if (button==null) { layout.addView(button); } else { layout.removeView(button); } break; default: break; } } @Override public void onAnimationEnd(Animation animation) { // TODO Auto-generated method stub Toast.makeText(this, "Анимация закончена", Toast.LENGTH_SHORT).show(); } @Override public void onAnimationRepeat(Animation animation) { // TODO Auto-generated method stub Toast.makeText(this, "Анимация повторяется", Toast.LENGTH_SHORT).show(); } @Override public void onAnimationStart(Animation animation) { // TODO Auto-generated method stub Toast.makeText(this, "Анимация стартовала!", Toast.LENGTH_SHORT).show(); } } |
package animationsample.com.com; import android.R.layout; import android.app.Activity; import android.graphics.Paint; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.animation.BounceInterpolator; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.TextView; import android.widget.Toast; public class AnimationSampleActivity extends Activity implements AnimationListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startAnimation(View view) { switch (view.getId()) { case R.id.Button01: //загружаем описание анимации из XML-файла Animation animation1 = AnimationUtils.loadAnimation(this, R.anim.myanimation); animation1.setAnimationListener(this); View animatedView1 = findViewById(R.id.rotatetext); animatedView1.startAnimation(animation1); break; case R.id.Button02: //показывает как объявить анимацию из кода //используется Interpolator (BounceInterpolator) Paint paint = new Paint(); TextView animatedView2 = (TextView) findViewById(R.id.scrolltext); float measureTextCenter = paint.measureText(animatedView2.getText().toString()); Animation animation2 = new TranslateAnimation(0f,-measureTextCenter,0.0f,0.0f); animation2.setDuration(5000); animation2.setInterpolator(new BounceInterpolator()); animatedView2.startAnimation(animation2); break; case R.id.Button03: //демонстрация эффекта затухания и добавление AnimationListener // TextView animatedView3 = (TextView) findViewById(R.id.fadeout); float from = 1.0f; float to = 0.0f; if (animatedView3.getVisibility()==View.INVISIBLE) { from = to; to = 1.0f; } Animation animation3 = new AlphaAnimation(from,to); animation3.setDuration(5000); animation3.setAnimationListener(this); animatedView3.startAnimation(animation3); break; case R.id.Button04: //демонстрация LayoutAnimation ViewGroup layout = (ViewGroup) findViewById(R.id.layout); Animation animation4 = new AlphaAnimation(0.0f, 1.0f); animation4.setDuration(5000); LayoutAnimationController controller = new LayoutAnimationController(animation4,0); layout.setLayoutAnimation(controller); View button = findViewById(R.id.Button03); if (button==null) { layout.addView(button); } else { layout.removeView(button); } break; default: break; } } @Override public void onAnimationEnd(Animation animation) { // TODO Auto-generated method stub Toast.makeText(this, "Анимация закончена", Toast.LENGTH_SHORT).show(); } @Override public void onAnimationRepeat(Animation animation) { // TODO Auto-generated method stub Toast.makeText(this, "Анимация повторяется", Toast.LENGTH_SHORT).show(); } @Override public void onAnimationStart(Animation animation) { // TODO Auto-generated method stub Toast.makeText(this, "Анимация стартовала!", Toast.LENGTH_SHORT).show(); } }
Вот, что на выходе должно получится:
Скачать исходный код приложения AnimationSample
Pingback: Написание виджета для Android | Программирование для мобильных устройств