Chapter 19. Animations and Interpolations

Here we will see how we can use the Animation class to make our UI a little less static and a bit more interesting. As we have come to expect, the Android API will allow us to do some quite advanced things with relatively straightforward code, and the Animation class is no different.

This chapter can be approximately divided into these parts:

  • An introduction to how animations in Android work and are implemented
  • An introduction to a UI widget we haven't explored yet, the SeekBar
  • A working animation app

First, let's explore how animations in Android work.

Animations in Android

The normal way to create an animation in Android is through XML. We can write XML animations and then load and play them in Java on a specified UI widget. So, for example, we can write an animation that fades in and out five times over three seconds, and then play that animation on an ImageView or any other widget. We can think of these XML animations as a script, as they define the type, order, and timing.

Let's explore some of the different properties we can assign to our animations, then how to use them in our Java code, and then finally, we can make a neat animations app to try it all out.

Designing cool animations in XML

We have learned that XML can also be used to describe animations as well as UI layouts, but let's find out exactly how. We can state properties of an animation that describe the starting and ending appearance of a widget. The XML can then be loaded by our Java code by referencing the name of the XML file that contains it and turning it into a usable Java object; again, not unlike a UI layout.

Here is a quick look at some of the animation property pairs we can state to create an animation. Straight after we have looked at some XML, we will see how to use it in our Java.

Fading in and out

Alpha is the measure of transparency. So, by stating the starting fromAlpha and ending toAlpha values, we can fade items in and out. A value of 0.0 is invisible and 1.0 is an object's normal appearance. Steadily moving between the two makes a fading-in effect:

<alpha
   android:fromAlpha="0.0"
   android:toAlpha="1.0" />

Move it, move it

We can move an object within our UI by using a similar technique; fromXDelta and toXDelta can have their values set as a percentage of the size of the object being animated.

The following code would move an object from left to right a distance equal to the width of the object itself:

<translate 
android:fromXDelta="-100%"
android:toXDelta="0%"/>

In addition, there are the fromYDelta and toYDelta properties for animating up and down.

Scaling or stretching

The fromXScale and toXScale values will increase or decrease the scale of an object. As an example, the following code will change the object running the animation from normal size to invisible:

<scale
android:fromXScale="1.0"
android:fromYScale="0.0"/>

As another example, we could shrink the object to a tenth of its usual size using android:fromYScale="0.1", or make it 10 times as big using android:fromYScale="10.0".

Controlling the duration

Of course, none of these animations would be especially interesting if they just instantly arrived at their conclusion. To make our animations more interesting, we can therefore set their duration in milliseconds. A millisecond is one thousandth of a second. We can also make timing easier, especially in relation to other animations, by setting the startOffset, also in milliseconds.

The next code would begin an animation one third of a second after we started it, and it would take two thirds of a second to complete:

android:duration="666"
android:startOffset="333"

Rotate animations

If you want to spin something around, just use fromDegrees and toDegrees. This next code, probably predictably, will spin a widget around in a complete circle because, of course, there are 360 degrees in a circle:

<rotate android:fromDegrees="360"
        android:toDegrees="0"
/>

Repeating animations

Repetition might be important in some animations, perhaps a wobble or shake effect, so we can add a repeatCount property. In addition, we can specify how the animation is repeated by setting repeatMode.

The following code would repeat an animation 10 times, each time reversing the direction of the animation. The repeatMode property is relative to the current state of the animation. What this means is that if you, for example, rotated a button from 0 to 360 degrees, the second part of the animation (the first repeat) would rotate the other way, from 360 degrees back to 0. The third part of the animation (the second repeat) would again reverse and rotate from 0 to 360 degrees:

android:repeatMode="reverse"
android:repeatCount="10"

Combining animation's properties with Set

To combine groups of these effects, we need a set. This code shows how we can combine all the previous code snippets we have just seen into an actual XML animation that will compile:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
  ...All our animations go here:
</set>

We still haven't seen any Java with which to bring these animations to life. Let's fix that now.

Instantiating animations and controlling them with Java code

This next snippet of Java code shows how we would declare an object of the Animation type, initialize it with an animation contained in an XML file named fade_in.xml, and start the animation on an ImageView. Soon we will do this in a project, and see where to put the XML animations as well:

// Declare an Animation object
Animation animFadeIn;

// Initialize it 
animFadeIn = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.fade_in);

// Get an ImageView from the UI in the usual way
ImageView (ImageView) findViewById(R.id.imageView);

// Start the animation on the ImageView
imageView.startAnimation(animFadeIn);

We already have quite a powerful arsenal of animations and control features for things such as timing. But the Android API gives us a little bit more than this as well.

More animation features

We can listen for the status of animations much like we can listen for clicks on a button. We can also use interpolators to make our animations more life-like and pleasing. Let's look at listeners first.

Listeners

If we implement the AnimationListener interface, we can indeed listen to the status of animations by overriding the three methods that tell us when something has occurred. We could then act based on these events.

OnAnimationEnd announces the end of an animation, onAnimationRepeat is called each and every time an animation begins a repeat, and—perhaps predictably—onAnimationStart is called when an animation has started animating. This might not be the same time as when startAnimation is called if a startOffset is set in the animations XML:

@Override
public void onAnimationEnd(Animation animation) {
   // Take some action here

}

@Override
public void onAnimationRepeat(Animation animation) {
   
   // Take some action here

}

@Override
public void onAnimationStart(Animation animation) {
   
   // Take some action here

}

We will see how AnimationListener works in the Animations demo app, as well as putting another widget, SeekBar, into action.

Animation interpolators

If you can think back to high school, you might remember exciting lessons about calculating acceleration. If we animated something at a constant speed, at first glance things might seem OK. If we then compared the animation to another that uses gradual acceleration, then the latter would almost certainly be more pleasing to watch.

It is possible that if we were not told that the only difference between the two animations was that one used acceleration and the other didn't, we wouldn't be able to say why we preferred it. Our brains are more receptive to things that conform to the norms of the world around us. This is why adding a bit of real-world physics, such as acceleration and deceleration, improves our animations.

The last thing we want to do, however, is start doing a bunch of mathematical calculations just to slide a button onto the screen or spin some text in a circle.

This is where interpolators come in. They are animation modifiers that we can set in a single line of code within our XML.

Some examples of interpolators are accelerate_interpolator and cycle_interpolator:

android:interpolator="@android:anim/accelerate_interpolator"
android:interpolator="@android:anim/cycle_interpolator"/>

We will put some interpolators, along with some XML animations and the related Java code, into action next.

Tip

You can learn more about interpolators and the Android Animation class on the developer website here: http://developer.android.com/guide/topics/resources/animation-resource.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.208.183