Animating Properties and Tweening Pages in Android 3-0

Exclusive offer: get 50% off this eBook here
Android 3.0 Animations: Beginner’s Guide

Android 3.0 Animations: Beginner’s Guide — Save 50%

Bring your Android applications to life with stunning animations.

€20.99    €10.50
by Alex Shaw | November 2011 | Beginner's Guides

In this article by Alex Shaw, author of Android 3-0 Animations Beginners Guide, we will build on the tweening techniques we've already learned, and also apply some new techniques that were introduced in Android 3.0.

In this article, we shall:

  • Use a ViewFlipper for animating a book-like application
  • Use Java to define a new tween animation and apply it to a view
  • Use an ObjectAnimator to apply an animation to a view, a bit like a tween
  • Use a ValueAnimator to generate values, which we will use for a more complex animation
  • Compare the Animator classes to the tween classes.

(For more resources on Android, see here.)

Note for developers using versions of Android before 3.0

So far, everything we have learned has been backwards-compatible with previous versions of Android. This will hold true for the first part of this article, but not the second. That is to say that ViewFlippers are backwards-compatible with previous versions of Android, but ValueAnimators and ObjectAnimators are new in version 3.0.

At the time of writing (mid-2011), the Android Compatibility Package does not help with this problem.

Turning pages with a ViewFlipper

ViewFlipper is a neat little wrapper class for applying a page-turning animation to a set of pages. It makes use of the tween animation classes, and extends them with an XML interface.

The ViewFlipper is actually a subclass of something called a ViewAnimator. Do not get confused! A ViewAnimator is a completely different class to a ValueAnimator or an ObjectAnimator, and they are not interchangeable.

Let's see more.

Time for action – making an interactive book

You have been hired by a children's book publisher to make an interactive book. The book will teach kindergarten children about different sorts of motion by showing them small animations on the pages.

First up, we will use a ViewFlipper widget to make an animated page-turning interface. What better way to learn about a page-turning widget than by using it to make a book? We will also add some simple pages to test the ViewFlipper, which we can add animations to in some later examples.

  1. Create a new Android project with the following settings:
    • Project name: Interactive Book
    • Build target: Android 3.0
    • Application name: Interactive Book
    • Package name: com.packt.animation.interactivebook
    • Activity: InteractiveBook
  2. The first thing we will do is to define a layout for our book. We want it to look a little bit like the following screenshot:
  3. So let's begin! Open res/layout/main.xml and create the following layout:
  4. <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ViewFlipper android:id="@+id/pages"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="2">
    </ViewFlipper>
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="center"
    >
    <Button
    android:id="@+id/prev"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:drawableLeft="@android:drawable/ic_media_previous"
    android:text="Previous" />
    <Button
    android:id="@+id/next"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:drawableRight="@android:drawable/ic_media_next"
    android:text="Next" />
    </LinearLayout>
    </LinearLayout>

  5. Here we have set up the layout of the application, but we have not yet added any pages. In XML, the pages of the ViewFlipper are created by adding child layouts to ViewFlipper.
  6. Firstly, we will want a Drawable, which we can animate. Create a new file in res/drawable called res/drawable/ball.xml and give it the following contents:
  7. <?xml version="1.0" encoding="utf-8"?>
    <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <gradient
    android:startColor="#FFFF0000"
    android:endColor="#FF551010"
    android:angle="270"/>
    <size
    android:height="40dp"
    android:width="40dp"/>
    </shape>

  8. This is just an ordinary ShapeDrawable; there's no special animation and stuff here! We will just use it as a simple ball graphic while we are writing the book. Later on, we will add animation.
  9. In main.xml, between the &ltViewFlipper> and </ViewFlipper> tags, add the following new elements: I will intersperse the code with pictures, so that you can see what we are adding as we go along. You should add the XML in order, and use the pictures as a quick guide to get what you want? First, take a look at the following screenshot. This should give you an idea of the structure of the page that we are going to make:
  10. Looks simple enough? Let's write the layout code for it. Remember that this is going between the &ltViewFlipper> and </ViewFlipper> tags.
  11. <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="This is a ball. It is a red ball."
    />
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/rollingball"
    android:src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="@drawable/ball"
    android:paddingLeft="60dp"
    />
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=
    "This red ball is rolling. Watch the red ball roll."
    />
    </LinearLayout>

  12. That was page 1, now let us make page 2. It will be laid out like the next screenshot:
  13. The layout text that follows should go between the &ltLinearLayout> for page 1 and the </ViewFlipper> tag.
  14. <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Look! This is a red ball too."
    />
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/bouncingball"
    android:src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="@drawable/ball"
    android:paddingLeft="60dp"
    />
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=
    "The ball is bouncing. See the ball bounce."
    />
    </LinearLayout>

  15. Finally, this is what the last page will look like:
  16. As you might suppose, the layout that follows goes between page 2 and the </ViewFlipper> tag.
  17. <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="The end. Now go and tidy your room."
    />

  18. Our content pages are defined in XML. Our ViewFlipper is going to treat each of the highest-level elements (the LinearLayout and the TextView) as pages in its layout. In this sense, it works exactly as a FrameLayout would work.
  19. Okay, great. If you ran this now, you would be able to see the first page, but we've still not connected the page-turning buttons. Let's do that now. Open up InteractiveBook.java and add the following import declarations:
  20. import android.view.View;
    import android.widget.Button;
    import android.widget.ViewAnimator;

  21. The last one is the most important. As I mentioned earlier, the ViewFlipper is a subclass of ViewAnimator. Seeing, as we don't need to use any of the methods of the subclass, we are only going to work with its superclass.
  22. Now, add the following block of code at the end of onCreate().
  23. final ViewAnimator pages =
    (ViewAnimator) findViewById(R.id.pages);
    Button prev = (Button) findViewById (R.id.prev);
    Button next = (Button) findViewById (R.id.next);
    prev.setOnClickListener(new View.OnClickListener() {
    public void onClick (View v) {
    pages.showPrevious();
    }
    });
    next.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    pages.showNext();
    }
    });

  24. Here we can see exactly how to write a page-turning control in a ViewFlipper. Simply call pages.showPrevious() or pages.showNext().
  25. Build and run your application. You should see that the ViewFlipper turns pages perfectly well now.
  26. There's something missing from this interactive book—the animation between the pages is not very smooth. In fact, all it does is switch between one page and the next. Let's give it a more natural feel with a page turning animation. In res/anim, create a new XML file called slidein.xml. This will be an ordinary tween animation. We will use this animation to introduce new pages to the screen. Add the following block of code to it:
  27. <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator">
    <translate
    android:fromXDelta="100%p"
    android:toXDelta="0"
    android:duration="500"
    />
    </set>

  28. This means that when the user turns a page, the new page comes across from the right-hand side of the screen, as if they were turning pages in a book (sort of).
  29. Now let's add the opposite effect, by removing the old page from the screen. In res/anim, create another XML file called – you guessed it – slideout.xml. In it, add the following XML:
  30. <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">
    <translate
    android:toXDelta="-100%p"
    android:fromXDelta="0"
    android:duration="500"
    />
    </set>

  31. As the pages arrive from the right, they also move off to the left.
  32. Now we need to add this animation to the ViewFlipper. Open up main.xml again, and add these attributes to our declaration of the ViewFlipper.
  33. <ViewFlipper android:id="@+id/pages"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="2"
    android:inAnimation="@anim/slidein"
    android:outAnimation="@anim/slideout" >

  34. Now build and run the interactive book. You will see that your pages now transition smoothly from one to the next.

What just happened?

We created a book-like application that displays several pages of information. We created a new ViewFlipper widget and applied a page-turning animation to it to give it a natural, book-like feel.

For convenience, the animations applied to ViewFlipper will apply to every single page that is contained within it. Remember, you do not need to apply an individual tween to each page in your book. Just adding the inAnimation and outAnimation in your ViewFlipper will be sufficient.

Have a go hero – improving the ViewFlipper

Think about how you would like to turn pages in a book. Perhaps the motion that we created above could be improved in some way.

Edit the slidein.xml and slideout.xml tween animations, and create a new animation of your own invention.

 

Android 3.0 Animations: Beginner’s Guide Bring your Android applications to life with stunning animations.
Published: November 2011
eBook Price: €20.99
Book Price: €34.99
See more
Select your format and quantity:

(For more resources on Android, see here.)

Creating tween animations in Java

So far, all of the tween animations we made have been created in XML, and there is good reason for this. Why should you want to clutter up your logical code with a load of presentation code?

But sometimes you want to create your tweens programmatically, perhaps because they rely on some computed values or it makes sense to describe them computationally.

Whatever the reason, we can use Java to create tween animations just as easily as we can create them in XML.

Time for action – creating a tween in Java

We want to make a new animation to replace slidein.xml. This time, we want our pages to come in from the right, as before, but we will add a scale animation too, to make it look more exciting. It will be as if the page is being pulled from a tall stack of pages, just out of view.

But we're bored of XML. Don't ask me why, perhaps it's because of all those pointy brackets. Give us the round parentheses of Java, we say! We will use the Java equivalent of the XML tags for &ltset>, &lttranslate>, and &ltscale> animations.

  1. Open up InteractiveBook.java and add the following import lines:
  2. import android.view.animation.Animation;
    import android.view.animation.AnimationSet;
    import android.view.animation.ScaleAnimation;
    import android.view.animation.TranslateAnimation;

  3. All these classes describe animations like the ones we made use of in XML.
    • &ltset> becomes AnimationSet
    • &ltscale> becomes ScaleAnimation
    • &lttranslate> becomes TranslateAnimation
  4. 2. Next, let's construct an AnimationSet, into which we can build a compound animation. Navigate to the bottom of the onCreate() method and add the following code:
  5. AnimationSet slideAndScale = new AnimationSet(true);

  6. This creates an AnimationSet. The Boolean true means that we want a shared interpolator. It's the Java equivalent of writing the following in XML (don't add this to your code!):
  7. <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="true">

  8. Now to create a translate animation, go into the &ltset>. Add the following code below our AnimationSet.
  9. TranslateAnimation slide = new TranslateAnimation(
    Animation.RELATIVE_TO_PARENT, 1f,
    Animation.RELATIVE_TO_PARENT, 0,
    Animation.RELATIVE_TO_SELF, 0,
    Animation.RELATIVE_TO_SELF, 0
    );

  10. The Java constructor for a TranslateAnimation lets you specify the fromX, toX, fromY, and toY components of the translation. The enumeration values are the equivalent of the different value types that you can input in XML.
  11. The options that you can specify are RELATIVE_TO_PARENT, RELATIVE_TO_SELF, and ABSOLUTE.
  12. Now to make a scaling animation.
  13. ScaleAnimation scale = new ScaleAnimation(
    10,
    1,
    10,
    1
    );

  14. Similar to the TranslateAnimation constructor, the arguments are fromX, toX, fromY, and toY, except that this time they are all floating-point multiplier values.
  15. 5. Now we add them in to the main
  16. AnimationSet
  17. as follows:

    slideAndScale.addAnimation(slide);
    slideAndScale.addAnimation(scale);

  18. Next, we want to specify the duration of the animation. As everything has been already added to the AnimationSet, all we need to do is add the following line:
  19. slideAndScale.setDuration(1000);

  20. As you probably expect, by now, 1000 is the duration in milliseconds to show the animation.
  21. This concludes the construction of the AnimationSet. So all we need to do now is to set it as the inAnimation on our ViewFlipper. We've already got access to the ViewFlipper object as pages, so we can simply add this:
  22. pages.setInAnimation(slideAndScale);

  23. There! Build and run your activity and observe the new animation.
  24. As you can see, the image now scales as the page is turned.

What just happened?

We've created a new page-turning animation, which is an AnimationSet, containing a ScaleAnimation and a TranslateAnimation. Now the page looks like it is being lifted into view, as it is turned.

We've created tween animations before, but this one was in Java. We have seen that it is possible to create a tween animation in Java that provides the same sort of functionality, which you would expect from a tween animation created in Java. By comparing the source against its equivalent in XML, you can see where the differences lie.

Android 3.0 Animations: Beginner’s Guide Bring your Android applications to life with stunning animations.
Published: November 2011
eBook Price: €20.99
Book Price: €34.99
See more
Select your format and quantity:

(For more resources on Android, see here.)

Writing the SlideAndScale animation in Java

In Java, we instantiate the AnimationSet, ScaleAnimation, and TranslateAnimation. The animation objects are parameterized in their respective constructors.

We then add the ScaleAnimation and TranslateAnimation to the AnimationSet.

AnimationSet slideAndScale = new AnimationSet(true);
TranslateAnimation slide = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 1f,
Animation.RELATIVE_TO_PARENT, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0
);
ScaleAnimation scale = new ScaleAnimation(
10,
1,
10,
1
);
slideAndScale.addAnimation(slide);
slideAndScale.addAnimation(scale);
slideAndScale.setDuration(1000);

Writing the SlideAndScale animation In XML

In XML, the tween animation is created by declaring a &ltset> tag that contains the translate and scale operations as child nodes. The animations are parameterized by giving them attributes.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true"
android:duration="500">
<translate
android:fromXDelta="100%p"
android:toXDelta="0"
/>
<scale
android:fromXScale="10"
android:toXScale="1"
android:fromYScale="10"
android:toYScale="1"
/>
</set>

As you can see, the advantage of the XML version is that it is more clearly laid-out. This is not just a matter of personal taste; by writing each attribute name as you assign it, there is never any ambiguity as to which value you are assigning. Look at the Java version and see if you can remember what order the constructor arguments are constructed in. It's hard, isn't it?

In conclusion, programmatic tween creation should only be used when you can think of a clear advantage.

Have a go hero – tweening using Java

Okay, now that we've made a tween that scales and slides in the graphic, have a go at making a similar tween for the outAnimation part of the interactive book.

Look at the code you've already written, and make a new animation in Java with the following properties:

  • As the page leaves the screen, it moves to the left
  • As the page leaves the screen, it gets larger

Animating with ObjectAnimator

ObjectAnimators are the first animations you will learn about, which are new in Android 3.0. Recall that tweens are all about moving views from one place to another, and that they describe different kinds of motion. Unlike tweens, animators work by updating values on an object in a much more programmatic way.

Animators just change numeric parameters on an object that they know nothing about, for instance, translating a view from one place to another. But by applying an animator to the X and Y coordinates of a view, an Animator can be used to perform the same task that a tween would do.

Which one you choose is up to you. Animators give you more flexibility, but they might not be as clear to read.

Time for action – animating the rolling ball

The children's book company has got back to us and they're not happy with the first page of our interactive book. It says that the ball is rolling, but it isn't! We're going to fix this by using an ObjectAnimator to move the ball backwards and forwards across the screen.

  1. Open up InteractiveBook.java and add a new import declaration: import android.animation.ObjectAnimator; This should come as no surprise! I already told you that we would be using the ObjectAnimator class.
  2. Next, go to the end of the onCreate() method, and add the following lines:
  3. View rollingBall = findViewById(R.id.rollingball);
    ObjectAnimator ballRoller =
    ObjectAnimator.ofFloat(
    rollingBall,
    "TranslationX",
    0,
    400
    );

  4. Underneath the code you just added, add the following.
  5. ballRoller.setDuration(2000);
    ballRoller.setRepeatMode(ValueAnimator.REVERSE);
    ballRoller.setRepeatCount(ValueAnimator.INFINITE);

  6. These terms should look familiar to the XML we wrote in the previous chapter, although the Java form will seem unfamiliar.
    • setDuration sets the duration of the animation in milliseconds
    • setRepeatMode can be either REPEAT or REVERSE
    • setRepeatCount can be an integer number of repeats or (as it is here) INFINITE
  7. One last line you need to add after all of this, is to tell Android to begin the animation immediately. ballRoller.start();
  8. And that's it! Couldn't be simpler. Build and run your activity and you will see that the ball on the first page now rolls backwards and forwards.
  9. This red ball is rolling, because we animated it!

What just happened?

Here we used our first Animator, and it is an ObjectAnimator. The ObjectAnimator provides a simple way to animate a scene by continuously updating a parameter of that scene.

In this article, we have made an interactive animation using the Android ViewFlipper class to make a page-turning interface. We also learned about the ValueAnimator and ObjectAnimator classes, which are new animation techniques in Android 3.0.

Summary

In this article, we learnt about the ViewFlipper class, ValueAnimator and the ObjectAnimator classes.


Further resources on this subject:


About the Author :


Books From Packt


Android 3.0 Application Development Cookbook
Android 3.0 Application Development Cookbook

Appcelerator Titanium Smartphone App Development Cookbook
Appcelerator Titanium Smartphone App Development Cookbook

Android Application Testing Guide
Android Application Testing Guide

Google App Inventor
Google App Inventor

Flash Development for Android Cookbook
Flash Development for Android Cookbook

Android User Interface Development: Beginner's Guide
Android User Interface Development: Beginner's Guide

Android NDK Beginner’s Guide: RAW
Android NDK Beginner’s Guide: RAW

Google App Engine Java and GWT Application Development
Google App Engine Java and GWT Application Development


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software