Android 3.0 Animations (动画)


Android 3.0 Animations Beginner's Guide Bring your Android applications to life with stunning animations Alex Shaw BIRMINGHAM - MUMBAI Android 3.0 Animations Beginner's Guide Copyright © 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: October 2011 Production Reference: 1211011 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84951-528-3 www.packtpub.com Cover Image by Vinayak Chittar (vinayak.chittar@gmail.com) Credits Author Alex Shaw Reviewers Nathan Schwermann Roger Belk Acquisition Editor Tarun Singh Development Editors Pallavi Iyengar Meeta Rajani Technical Editors Lubna Shaikh Ankita Shashi Copy Editor Leonard D'Silva Project Coordinator Shubhanjan Chatterjee Proofreaders Stephen Silk Samantha Lyon Indexer Monica Ajmera Graphics Geetanjali Sawant Production Coordinator Melwyn D'sa Cover Work Melwyn D'sa About the Author Alex Shaw has been an Android fan boy since Android 1.5 arrived, and he began developing software for it almost immediately. He has presented at DroidCon in Berlin and London, and written applications for business, academia, and pleasure. An alumnus of The University of Edinburgh, he has kept close business and social ties with the Scottish geek scene. His consulting company, Glastonbridge Software Limited, provides development resources to the Edinburgh software industry. In his spare time, he writes generative music applications and talks a lot of nonsense. Hearty thanks to my partner, Amy Worthington, for putting up with my constant stream of ideas whenever writing was on my mind. Thanks also to my Mum and to my close friends, who have supported me when stress and anxiety were taking their toll. Thanks also to the team at Packt, who put up with my erratic e-mail discipline and occasional late submissions, with patience and kindness. This book has been an adventure and an experience to remember. About the Reviewers Nathan Schwermann is a husband and proud father. He attends the University of Kansas to study Computer Science. In the past years, Nathan has worked as a freelance Android developer, making many great applications to help pay his high tuition costs. Nathan aspires to work for an independent gaming studio. Roger Belk, also known as Big Daddy App, has developed Android applications for the last year. He is a self taught 43-year-old Ironworker. He builds applications using Eclipse with Android SDK, Java, and Google's App Inventor. You can check out his website at www.BigDaddyApp.com Roger is also a power user in Google's App Inventor forums, answering help requests from new AI developers, from the setup, to the How-To, and to the coffee shop just chatting and kicking around ideals for AI apps. Books that he has worked on include Animation 3.0 and Google App Inventor. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.  Why Subscribe? ‹‹ Fully searchable across every book published by Packt ‹‹ Copy and paste, print and bookmark content ‹‹ On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: Animation Techniques on Android 7 An animated application: counting calculator 8 Time for action – learning to count with the counting calculator 8 Frame animation 10 Time for action – playing with the frames 11 Fancy frame animations 13 Simple fades using transition animations 14 Tweening 14 Time for action – finding tweens 15 The tween jazz band 15 Interpolations—meet the drummer 16 Animation sets—meet the conductor 16 Tweening elements in XML 16 What are tweens good at? 17 Animators – new in Android 3.0! 17 Beyond views: high-speed animating in 2 dimensions 19 Drawing loops 19 Doing your own housekeeping is hard 20 Where to use surfaces 21 What do views do anyway? 21 Time for action – let's draw views 21 Animating awesome 3D 27 Want to go faster? 28 Making a better application 30 Always be helpful 30 Small and powered by batteries 30 Summary 32 Table of Contents [ ii ] Chapter 2: Frame Animations 33 Making a frame animation 34 Time for action – the funky stick man 34 The anatomy of a frame animation 38 XML elements 38 39 39 Timing 40 Images and Drawables 40 Screen size 41 Sometimes you run out of memory 41 Making frame animations in Java 43 Time for action – making the stick man interactive 43 Controlling frame animations 48 start() and stop() 48 AnimationDrawable.setVisible(true,true) 48 Creating new animations 48 Time for action – programmatically defined animation 48 More neat methods on AnimationDrawable 52 Working properly in the GUI thread 53 Animating a transition between frames 55 Time for action – make the transition 55 Writing XML for a transitionDrawable 59 59 59 Working with other useful methods 60 startTransition(int duration) 60 reverseTransition(int duration) 60 resetTransition() 60 Summary 62 Chapter 3: Tweening and Using Animators 63 Greeting the tween 63 Time for action – making a tower of Hanoi puzzle 64 Defining starts and ends 67 Assembling the building blocks of a tween 68 Time for action – composing a tween animation 68 Taking a look at the different types of tween animation 74 74 74 75 75 Common attributes 76 Declaring tweens in the correct order 76 Table of Contents [ iii ] Making tweens that last for ever 77 Time for action – creating an everlasting tween 77 Animating layouts 81 Time for action – laying out blocks 81 Receiving animation events 83 Time for action – receiving animation events 84 Interpolating animations 86 Time for action – changing the rhythm with interpolators 86 Using the interpolators provided by Android 88 Linear interpolator 88 Accelerate interpolator 88 Decelerate interpolator 88 Accelerate-decelerate interpolator 88 Bounce interpolator 89 Anticipate interpolator 89 Overshoot interpolator 89 Anticipate overshoot interpolator 89 Cycle interpolator 89 Sharing interpolators 89 android:sharedInterpolator="true" 90 android:sharedInterpolator="false" 90 Creating and parameterizing interpolators 90 Finding out more 91 Summary 92 Chapter 4: Animating Properties and Tweening Pages 93 Note for developers using versions of Android before 3.0 94 Turning pages with a ViewFlipper 94 Time for action – making an interactive book 94 Creating tween animations in Java 103 Time for action – creating a tween in Java 104 Writing the SlideAndScale animation in Java 107 Writing the SlideAndScale animation In XML 107 Animating with ObjectAnimator 108 Time for action – animating the rolling ball 109 Constructing ObjectAnimators 111 Breaking down the construction of ballRoller 111 Getting and setting with ObjectAnimators 112 Animating values with ValueAnimator 113 Time for action – making a ball bounce 113 Updating the frame rate 117 Changing the interpolator 117 Time for action – improving our bouncing ball 117 Comparing animators and tweens 119 Table of Contents [ iv ] Advantages of animators 119 Advantages of tweens 119 Things that are common between animators and tweens 119 Summary 119 Chapter 5: Creating Classes for Tween Animation 121 Creating multi-variable Animators 121 Time for action – making an animated Orrery 122 The structure of the Orrery 129 Animating LayerDrawables 129 PropertyValuesHolder 130 Helpful ValueAnimator parameters 130 Using objects as parameters for value animations 130 Time for action – animating between objects 131 Using a TypeEvaluator 135 Setting Keyframes 135 Time for action – defining fixed points with Keyframes 136 Using the Keyframe 137 Keyframe timing 138 Combining Fragments and XML Animators 139 Time for action – adding a Description Pane 140 Declaring ObjectAnimator attributes 143 Customizing the interpolator classes 144 What do interpolators do? 144 Time for action – making a teleport interpolator 145 Interpolator value ranges 148 Summary 149 Chapter 6: Using 3D Visual Techniques 151 Understanding 3D graphics 151 Showing depth with 3D effects 153 Raising elements 153 Time for action – making a jigsaw with lifting pieces 153 Laying out the jigsaw 161 Special classes we created to help animation 162 Scaling the image with ScalableImageView.SetDepth 162 Moving pieces with PieceSwapper 162 Completing the animation with PieceSwapper.onAnimationEnd 163 Adding drop shadows 163 Time for action – using shadows with our jigsaw 163 Conjuring up a change in focus 167 Table of Contents [ v ] Time for action – changing the focus of the jigsaw 167 Setting the image focus on a RaisableImageView 170 Applying image focus to the whole jigsaw 170 Creating 3D rotations 171 Time for action – spinning jigsaws 172 Examining Rotate3DAnimation.java 174 Extending a tween animation 176 initialize (int width, int height, int parentWidth, int parentHeight) 176 applyTransformation (float interpolatedTime, Transformation t) 176 Describing transformations with a Matrix (android.graphics.Matrix) 176 Doing 3D transformations with a Camera (android.graphics.Camera) 177 rotateX (float), rotateY (float), rotateZ (float) 177 translate (float x, float y, float z) 177 save() and restore() 177 Summary 179 Chapter 7: 2D Graphics with Surfaces 181 Introducing game loops 182 Drawing a surface on the screen 182 Time for action – animating bubbles on a surface 183 The design of the Bubbles application 193 Investigating Bubble.java 193 Investigating BubblesView.java 194 Seeing the game loop in action 195 Using a SurfaceView 196 Using a SurfaceHolder 196 lockCanvas 196 unlockCanvasAndPost 196 Using a SurfaceHolder.Callback 197 surfaceCreated (SurfaceHolder holder) 197 surfaceDestroyed(SurfaceHolder holder) 198 surfaceChanged(SurfaceHolder holder, int format, int width, int height) 198 Using the Canvas as an animation tool 199 Time for action – making more realistic bubbles 199 Getting to know the drawing tools in Canvas 204 drawBitmap and drawPicture 205 drawCircle 205 drawColor and drawPaint 205 drawLine and drawLines 205 drawOval and drawArc 205 drawPath 205 drawRect and drawRoundRect 205 drawText and drawTextOnPath 205 Table of Contents [ vi ] Using Paint effects 206 setAlpha 206 setAntiAlias 206 setColor 206 setStrokeCap 206 setStrokeWidth 206 setStyle 206 setTextAlign 207 setTextScaleX 207 setTextSize 207 setTypeface 207 Frame scheduling 207 Time for action – creating smooth game loops 207 Adjusting the frame duration 210 Taking the wait out of the game loop 210 Summary 212 Chapter 8: Live Wallpapers 213 Creating a live wallpaper 213 Time for action – making our first live wallpaper 214 Declaring a live wallpaper 219 How live wallpapers appear 219 Understanding services 220 WallpaperService 220 Adding interactivity to live wallpaper 223 Time for action – making soapy fingers 223 Enabling WallpaperService.Engine interaction 228 Registering live wallpaper interaction 228 Using live wallpaper preferences 230 Time for action – configuring a live wallpaper 231 Updating preferences as soon as they are set 237 Time for action – updating live wallpaper configuration 237 Connecting our wallpaper to our prefereces 239 Disconnecting our preferences when our wallpaper exits 239 How the user will see preferences 239 Storing preferences with SharedPreferences 240 Reading from SharedPreferences 240 Writing to SharedPreferences 240 OnSharedPreferenceChangedListener 241 Composing preference XML 241 Defining preferences in XML 241 Setting attributes on XML preferences 242 Summary 244 Table of Contents [ vii ] Chapter 9: Practicing Good Practice and Style 245 Using focus and metaphor 246 Looking at focus 247 Time for action – don't confuse me with animation! 247 Getting to grips with metaphors 250 Time for action – getting messages from houses 251 Focus, redux 254 Maintaining consistency within an application 254 Reducing power usage 255 Time for action – measuring battery usage with PowerTutor 256 Precise estimation 258 Changing the Application Viewer Timespan 258 PowerTutor-supported devices 258 Optimizing an animation for power 259 Looking for problems 259 Time for action – identifying a problem 259 Finding the power hogs 260 Time for action – tracing to find optimizations 261 Removing the gremlin 264 Time for action – squashing gremlins that use too much power 264 Optimizing using an easy recipe 267 Summary 270 Appendix: Pop Quiz Answers 271 Chapter 1: Animation Techniques on Android 271 View animations and Drawable animations 271 Putting it all together 271 Chapter 2: Frame Animations 272 Making frame animations 272 Controlling frame animations 272 Transition Drawables 272 Chapter 3: Tweening and Using Animators 272 All those tweens! 272 AnimationListeners 273 Interpolators 273 Chapter 4: Animating Properties and Tweening Pages 273 ViewFlippers 273 Java tweens 273 ObjectAnimators 273 Value Animators 273 Table of Contents [ viii ] Chapter 5: Creating Classes for Tween Animation 274 PropertyValueHolders, ObjectAnimators, and TypeEvaluators 274 Fragment Animation and XML Animators 274 Custom interpolators 274 Chapter 6: Using 3D Visual Techniques 274 Depth effects 274 3D rotations 274 Chapter 7: 2D Graphics with Surfaces 275 Surface animations 275 Chapter 8: Live Wallpapers 275 Live wallpapers 275 Interactivity 275 Preferences for live wallpapers 275 Chapter 9: Practicing Good Practice and Style 276 Usability 276 Power usage 276 Index 277 Preface Android 3.0 Animation, a Beginner's Guide, will introduce each of the most popular animation techniques to you as an Android developer. Using step-by-step instructions, you will learn how to create interactive dynamic forms, moving graphics, and 3D motion. You will be taken on a journey from simple stop motion animations and fades through to moving input forms, and then on to 3D motion and game graphics. In this book we will create standalone animated graphics, three-dimensional lifts, fades, and spins. You will become adept at moving and transforming form data to bring boring old input forms and displays to life. What this book covers Chapter 1, Animation Techniques on Android, is a guided tour of the diverse possibilities for animating content on Android. Chapter 2, Frame Animations, teaches you to create and control animations that are composed of a series of still images. Chapter 3, Tweening and Using Animators, adds animated life to the Views in your Android application. Chapter 4, Animating Properties and Tweening Pages, introduces some more specialized animation capabilities, available in Android. Chapter 5, Creating Classes for Tween Animation, shows you how to take control of the low- level behaviors of your animations to create new and distinctive movements. Chapter 6, Using 3D Visual Techniques, takes techniques that we introduced in previous chapters and shows you how to use them to create 3D depth and rotation effects. Chapter 7, 2D Graphics with Surfaces, introduces programmatic animations that you draw onto a blank canvas. This technique is ideal for writing games and advanced visualizations. Preface [ 2 ] Chapter 8, Live Wallpapers, shows you how to build your animations into one of Android's most distinctive graphical features – wallpapers that move. Chapter 9, Practicing Good Practice and Style, shows you how animation can be used to make your application better looking and easier to use, as well as looking at the performance cost of animated graphics. What you need for this book You should know how to program in Java and have experience using the Android SDK to make Android applications. You should understand basic object-oriented programming and know how to run your code on an Android device. You should also understand that Android uses XML files to show Views on screen. You will require a computer that has the Android SDK installed and which has the Android 3.0 packages. You will also need a tool for entering the example code, compiling it, and deploying to an Android device or emulator. For this purpose, the book has been written with Eclipse users in mind, but the concepts and code presented will work equally well in IntelliJ IDEA or any other Android development environment that you are familiar with. Because the Android applications in this book can be run on real devices, you may want to have an Android 3.0-compatible device, or higher. This is not necessary, but it is much more fun! Who this book is for If you are familiar with developing Android applications and want to bring your apps to life by adding smashing animations, then this book is for you. This book assumes that you are comfortable with Java development and have familiarity with creating Android Views in XML and Java. The tutorials assume that you will want to work with Eclipse, but you can work just as well with your preferred development tools. Conventions In this book, you will find several headings appearing frequently. To give clear instructions of how to complete a procedure or task, we use: Time for action – heading 1. Action 1 2. Action 2 3. Action 3 Preface [ 3 ] Instructions often need some extra explanation so that they make sense, so they are followed with: What just happened? This heading explains the working of tasks or instructions that you have just completed. You will also find some other learning aids in the book, including: Pop quiz – heading These are short multiple choice questions intended to help you test your own understanding. Have a go hero – heading These set practical challenges and give you ideas for experimenting with what you have learned. You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "Get the example android project, CountDroid, from the code bundle and compile it to an Android APK for deploying to a device." A block of code is set as follows: package com.packt.animation.viewexample; import android.app.Activity; import android.os.Bundle; public class ViewExample extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyTextView helloView = new MyTextView(this); helloView.setText("Hello Views!"); setContentView(helloView); } } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: " Download the APK you built to your favorite emulator or Android device, and launch the Counting Calculator activity.". Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Preface [ 5 ] Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it. 1Animation Techniques on Android There are so many ways to make an animation on Android that you might get a little lost if you don't know where to start. So here is the grand tour! You'll find out how all the techniques in this book can be used to make your application stand out from the rest. Animations are divided loosely into a spectrum. At the top of the spectrum there are the simplest kinds of animation, and at the bottom there are the most complex kinds. In this chapter, we shall look at the following: ‹‹ Animations that just show the same animation every time you play it. Or, if they do change, then they follow some simple pre-defined pattern. These are frame animations. ‹‹ Animations that apply to a widget-based application, which take an ordinary input form and move it around in a way that means something. These are the tweens and the animators. ‹‹ Animations that can show anything calculated on the fly from whatever data they are given. Games are made like this. These are the surface-based animations. Android lets you combine these three techniques, but you get to choose them. Let me show you what I mean. Animation Techniques on Android [ 8 ] An animated application: counting calculator Let's get started by presenting an example showing many different types of animation. Counting calculator is a very simple calculator application, which is designed to familiarize children with the idea of adding two numbers together. To make it easy-to-use, animated elements direct the child's attention to the things that happen as they use the calculator. And for slightly older users (that would be us), we can see how Android brings animation to an interactive application. Time for action – learning to count with the counting calculator We'll get started by trying out the counting calculator right now! 1. Get the example android project, CountDroid, from the code bundle and compile it to an Android APK for deploying to a device. 2. You can build it either straight from the command line using Ant, or import it into Eclipse using Existing projects into workspace from the Import… dialog. 3. Download the APK you built to your favorite emulator or Android device, and launch the Counting Calculator activity. 4. Wait for the calculator to appear. Notice that whenever something happens, it is animated: 5. Press a number key and watch what happens. What do you think will happen when you press another number? Chapter 1 [ 9 ] 6. Press another number and watch what happens. You'll see an animated visualization in the top-half of the display: Animation Techniques on Android [ 10 ] What just happened? The first thing you'll see is the animated splash screen, which displays a short sequence introducing the application, and then you are delivered to the calculator itself. The splash screen is decorative; it's a little canned sequence to announce the purpose of the application in a fun way. The number buttons are animated, and so is the display. As you choose numbers, you'll see an animation on the top of the screen, counting the number of balls. There are several different sorts of animations, each expressing a different sort of meaning in the application. Have a go hero – explore the counting calculator application We're only just getting warmed up, but some people just have to see the code right away! If you are a fearless code explorer yourself, open up your favorite editor and have a look at the XML and Java elements of the Counting Calculator application. If you find anything confusing right now, don't panic! The animation concepts in the Counting Calculator will be explained throughout this book. Here is a handful of clues to get you started: ‹‹ There is a simple animation in res/drawable, defined in XML. Look in this folder for the splash.xml file. ‹‹ There are a few small animations in the res/anim folder. They are used elsewhere in the application layout. ‹‹ There is a big complex animation in BallField.java. See if you can work out which animations apply to which part of the user interface in the Counting Calculator. Frame animation The first sort of animation we'll look at is the animation that we used to make the splash screen. It's called a frame animation. Using this technique, you make an animation by creating several images and displaying them one after the other, like a strip of cinema film. Chapter 1 [ 11 ] It's exactly like making a film from a reel of still cells, or drawing a series of pictures in the corner of a book and flicking through them. Each frame is shown for a very short time before moving on to the next one, so that the eye does not realize that the images are distinct. Frame animations The term frame animation comes from movies, where it was considered that individual cells of a film resembled tiny framed pictures. Just remember that it works by showing a series of similar pictures, one after another. Because all animation works by making a series of updates to a picture, you will sometimes hear me using the word frame to describe other animation techniques. Don't be confused! When I am talking about Android frame animations, I will make sure I say the exact term "frame animation". Time for action – playing with the frames Time for some fun with frame animations! Let's have a play with the one in the splash screen of the Counting Calculator. Right now, we'll play around with changing the images; I'll show you the code part in the next chapter. 1. Open up your favorite image editor; anything that handles the PNG graphics format will do. If you have an editor that supports layered graphics, you might find it easier to load all the images as different layers, rather than loading every picture individually. Yours truly favors the GIMP for this purpose. 2. In your image editor, choose the option to open a file. Browse to the folder that contains the CountDroid project and navigate to the res/drawable directory from there. Select and load the images marked as splash_*.png. Animation Techniques on Android [ 12 ] In the previous screenshot, you can see a selection of frames taken from the Counting Calculator splash screen. Take a look at the images in order, and see how the images are all individual moments of the overall animation. 3. Try making some changes to the graphics. Add a dot on each image, in a slightly different place each time. 4. Save all of the images that you changed, so that they overwrite the existing images in the res/drawable folder. 5. If you are using Eclipse, refresh the res/drawable folder by selecting it in the Package Explorer and pressing F5. This will ensure it knows that it needs to recompile your APK. 6. Go back to your CountDroid project and rebuild it. Download the new version of the application to your device. 7. Load up the new application and watch its splash screen. 8. Go back to step four and play around! Get used to making things happen, by changing them incrementally. Can you make the dot appear to move in a straight line? What just happened You've just seen where the true work of the splash animation is done—we drew it! The animation we made is quite jerky, and that is because it is being redrawn every 100 milliseconds. For totally smooth playback of animation, the human eye needs to be shown a new image at least once every 42 milliseconds. At faster speeds, you need to make more frames for your animation, or they will finish too soon. If you go too fast, the graphics in most mobile devices will not be able to keep up and will drop frames. And the human eye will not notice the difference anyway. 100 milliseconds are enough for us to see an animation without getting too bored making it, although it does look rather jerky for now. You now know how to make things move around by changing frames, and this is exactly how professional animators all over the world do it (well, maybe you need a few more tools to make a Hollywood blockbuster, but the principle is the same). This technique is ideal when: ‹‹ Making animated graphics such as progress spinners and eye-catching game avatars ‹‹ Re-using existing animated graphics, for instance, animations that have been prepared for the web. Chapter 1 [ 13 ] ‹‹ Showing that something is happening behind the scenes, such as a file copying widget that shows files moving to their destination. ‹‹ Keeping it simple! It's a simple process, and if you work with non-technical designers and artists, they will be able to understand it easily. Android provides an API for creating these sorts of animations in XML, and I'll show you how to make your own in Chapter 2, Frame Animations. Fancy frame animations You might be thinking that frame animations are just for playing back pre-made animations, but that's not quite the whole story. Since Android is a bit more advanced than ordinary paper, you can do a lot more with it. ‹‹ You can apply playback controls to a frame animation by using Java. This means that you can pause the animation, speed it up, slow it down, and so on, as your application changes. ‹‹ You can add images and you can remove images from the animation. As they are graphical elements, the frames of the animation use the same graphics scaling techniques that other static graphics use. Let's say you use a lot of animations having only a couple of frames that are different. You could implement them all as only one animation, and add the right frames to it when you show it to the user. So although your pictures are drawn and added into the application as static elements, you can still make your animations interactive by choosing what you want to show next. Animation Techniques on Android [ 14 ] Simple fades using transition animations Sometimes you don't want to make a complex animation using lots of frames, but you would like to transition smoothly between two drawables without having to provide the in-between graphics as separate images. If you are in this position, you can use transition animations. Transition drawables are another type of drawable element that does simple fades between two images. Although the idea of them is a little bit different to frame animation, you will find that they work in a similar way. I'll demonstrate this to you in Chapter 2, Frame Animation. Tweening Tweening is short for in-betweening. It provides the vital link between two fixed points or key frames. Android provides a simple way to declare an animation that you can apply to your existing application. This time around, you don't need to add any extra graphics as you did with the XML animation. Instead, you use the views and widgets that are already in your application, making your widget-based interface itself represent dynamic content. You can move views around, distort them, make them vanish, or appear in all sorts of interesting ways. Google likes to call these animations tweens, taking a graphical element between one state and the next. A simple tween takes the display from one place to another. In the preceding diagram, the centre ball represents the tween. .Calculator make use of translations flying into the trash can. All of the tween animations that you will have seen in the Counting showing where things are going, such as songs being added to a playlist, or deleted items Translatons are an animation that moves a view from one place to another. This is great for The tween jazz band that transition behind the scenes with an appropriate animation on its screen. A networked application might take a few seconds to fetch a bit of data. You can represent sliding to its new destination. vanishes and reappears, then it just looks jerky. A tweening animation would show the piece A chess game might move between two different squares on the board, but if the piece just that you'll see later, but views are simple and consistent. views system to display information. There are other ways to display text and write buttons class. Animation classes were chosen for this purpose, because I wanted to use the Android numbers, and that's exactly right. When they move around, it's all thanks to the Animation You probably saw that the display and the buttons were just simple TextViews and What just happened? using a standard View class. All animations apply to views, so look for things that might be implemented Finding the tween animations in an application Animation class. As you use the application, look for animations that might be using the 2. Open up the Counting Calculator on your Android device. 1. been used. Let's take a look around the Counting Calculator application, and see where tweens have Time for action – finding tweens tween animations. several pre-made animations or write your own. Let's drill down into what we can do with keeps this sort of thing neatly encapsulated, your Java will look clean too. You can pick from By using this class and its subclasses, you can not only write great XML animations, but as it To implement tweening, Android uses a neat little class called, unsurprisingly, Animation. [ 15 ] Chapter 1 Animation Techniques on Android [ 16 ] Alpha animations, as their name implies, can shift the alpha value of a view from invisible to translucent to solid, or vice versa. By fading view elements gently in and out, you can change the focal point of your application in a smooth way. Rotate animations, well, you should be able to guess what this does. Scale animations make things bigger and smaller. This can be used effectively to add a 3D feel, without having to mess around with the mathematics of true 3D. Interpolations—meet the drummer Every animation needs an interpolator. Interpolators are separate classes that control animations, by telling them how fast they should be doing things. Modulating the speed of the animation as it goes along makes the character of the animation change. There are several built-in interpolator types that completely change the character of an animation. For instance, an accelerate interpolator makes the view accelerate to its destination. On the other hand, a bounce interpolator would make an animation bounce back-and-forth as it reaches its destination, giving the feeling of a ball coming to a rest. The bounce interpolator has a much more playful character, and is therefore more suited to fun applications than to an application that should look businesslike. You can think of interpolations as being the drummer in the band, as they control the rhythm of the animation. Animation sets—meet the conductor If an interpolation is the drummer, an animation set is a conductor. Using an animation set consisting of several different animations, you can make more interesting things happen to a view. You can combine animations at the same time, for instance, a rotating-scaling animation might make an object appear to corkscrew into or out of the screen. You can also combine animations in sequence, for instance, a translate tween followed by a scale tween would make an object appear to move, reach its destination, and then get bigger or smaller. You can even combine animation sets. Tweening elements in XML You can apply a transition animation in several places in your code. In fact, if you're writing in Java, you can set one off at any point. But Android provides entry points for animations in a few places, which are listed as follows: Chapter 1 [ 17 ] ‹‹ When the window first appears on screen, an animation can be used to show the view being put in place. This can also be used whenever the screen changes, for instance, due to portrait-landscape rotation. ‹‹ When you interact with some widgets, you can call an animation to make the interaction smoother. ‹‹ When you change pages on a book-style application, you can animate the switch to the next page. What are tweens good at? You're probably getting a feel for how you're expected to use animations by now. To sum up, they're suitable for use in situations like the following: ‹‹ Working with existing display elements ‹‹ Displaying secondary data to give the user information about the transition behind the scenes ‹‹ Encapsulating transforms on display elements, not just for XML but also to keep your Java code tidy too Animators – new in Android 3.0! As you are no doubt aware that views in Android GUIs have many accessors defining their position, their color, and so on, wouldn't it just be simpler to animate a view by changing those parameters a little bit each frame? This feature has been introduced in Honeycomb; it's called an Animator. At its most basic level, animators are little daemon threads that wake up, change a view a bit, and go back to sleep till the next frame. They are a lot like the old Animation classes for tweening, but they are more generalized. For instance, an Animator would allow you to modify the background color of a view, something that no tween could do. And if you have implemented your own views with special properties, they will work for those too. However, unlike a tween, they are not designed to go between two states. If you want that sort of functionality, you will have to program it yourself. They are also less descriptive to use in your code—a tween allows you to say "translate this object 200 pixels on the X-axis", but an Animator says "increment the X parameter by 200 pixels". I will show you how they compare to tweens in more detail in Chapter 3, Tweens and Animators. Animation Techniques on Android [ 18 ] Pop quiz – view animations and drawable animations Okay, it's time for you to see what you've learned so far! We've talked about two different sorts of animation: the ones you can use with pictures and the ones that you can use with view elements. There are a lot of ideas floating around; what can you remember? 1. What is a transition drawable? a. A view that switches between two views b. A drawable that switched between two drawables c. A view that switches between two drawables 2. You would like a tween to move faster towards the end of its animation. What parameter of the tween would you use to do this? a. Its interpolator b. Its grandmother c. Its animator 3. You have a set of PNG images that you want to combine into an animation. You would use… a. An animator b. An interpolator c. A frame animation 4. Which of the following animates views moving from one place to another? a. An animator b. A slider c. A tween 5. In the counting calculator, which of these animations is least likely to use a tween? a. The bouncing balls b. The equation display c. The keypad Chapter 1 [ 19 ] Beyond views: high-speed animating in 2 dimensions This is where things get really exciting! Sometimes you want to draw things to a screen and have full control over how they're drawn. This is especially true for animated elements, where you might want to draw some visualizations in real time. For instance, a graphic equalizer that moves in time with a playing MP3. You could draw it completely using views, but it would be horribly slow, and your phone would drain its battery much faster. This is because views do lots of extra work that makes them excellent for general interaction, like drawing themselves, handling clicks correctly, and so on. But that's not always useful, and it takes time. If only you could tell Android that you want to reserve an area of your screen for drawing freely, where you can look after the redrawing yourself, and optimize it for whatever your application does. Well don't worry, because you can do exactly that! Surfaces are raw areas of screen that you can draw whatever you like into. You can refresh them when you want, handle user touches however you like, and you even get a handy toolkit of common vector and bitmap drawing operations to make use of. If frame animations are like films, surface-based animations are like clockwork toys. Each thing has to be told programmatically how it should appear on the screen. Look at the bouncing balls in the Counting Calculator example; each one of those is drawn by a bounce routine and a count routine that manipulates everything about them. Drawing loops One thing that you will need to do when you are drawing animations like this is to keep updating the image with the next piece of the animation. Usually, you will find that you want to make incremental changes to your animation model at regular intervals, and then update the screen to represent it. This is a common pattern, especially in game programming. In your code, you make a loop that looks like the following screenshot: Animation Techniques on Android [ 20 ] This is what your loop will look like, if there are no external interactions with your animation or if the calculations in Calculate Display are modified top down by a supervising object (as it was for the ball animation in the Counting Calculator). But if you are writing something that handles user interactions in its own way, you will want to add in a separate stage to handle this. This is commonly called a game loop in games programming, and forms the basis for most applications that involve game-like interaction between a computer and a user. You will find that writing animation loops and game loops is in itself fairly simple, but you'll need to make sure that you write one when you're using a surface to handle your animations. Doing your own housekeeping is hard If you wanted to rewrite your entire application on a surface, you'd probably get something up and running pretty quickly, but you'd then spend weeks trying to reproduce all of the nice features that your TextViews and ListViews gave you. So don't do this as it's not worth it (I've tried), just take it from me. Chapter 1 [ 21 ] Where to use surfaces You can use surfaces in the following scenarios: ‹‹ When you want to compute the appearance of your animation, rather than follow a predefined pattern ‹‹ When you are making something that doesn't follow the widget-based interaction model ‹‹ When you are making something that needs to run fast ‹‹ Games ‹‹ Live wallpapers ‹‹ DSP and music visualizations (maybe that's just me) What do views do anyway? How should you decide that views are too complex and you should use a surface? As a simple example, we'll look at how views are drawn to the screen. It will help us see a little more into what views do behind the scenes, and go some way to explain why views are better for form data and why surfaces are fast. We will take a look at a slightly modified version of the Hello World application that the Eclipse ADT plugin generates for you, automatically. I recommend that you use Eclipse, because it provides you with an integrated suite of debugging tools, and because it helps you navigate your code easily. When you have a complex form, the routines we will see being called in the example would be triggered a lot, and for many view objects. Time for action – let's draw views For this example, we will create our own TextView class and breakpoint into it. Fortunately, for us, we will be able to base it on the android.view.TextView class, so the amount of code we need to write is minimal. 1. Create a new Android project in Eclipse. I will describe this particular example in Eclipse, because it provides easy access to the Java debugger. However, you can substitute your preferred development tool, if you are comfortable with using breakpoints in it. Animation Techniques on Android [ 22 ] 2. On the New Android Project page, enter the following settings and hit the Finish button: ‰‰ Project Name: ViewExample ‰‰ Build Target: Android 3.0 ‰‰ Package Name: com.packt.animation.viewexample ‰‰ Create Activity: ViewExample Chapter 1 [ 23 ] 3. Create a new class in the com.packt.animation.viewexample package, called MyTextView. It should override android.widget.TextView, and implement a constructor MyTextView(Context). Your class should look like this: package com.packt.animation.viewexample; import android.content.Context; import android.widget.TextView; public class MyTextView extends TextView { public MyTextView(Context context) { super(context); } } You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub. com/support and register to have the files e-mailed directly to you. 4. Click the Source menu and choose Override/Implement Methods.... Animation Techniques on Android [ 24 ] 5. There are a lot of methods there, aren't there? They represent functionality that the views system provides for free. (If you're not using Eclipse, skip to point 7). 6. Select the onDraw(Canvas), onLayout, and onMeasure(int, int) methods (you'll need to expand the view's parent class to see onLayout) and continue. 7. You will need to add one new constructor to the class. It will end up looking like the following block of code: package com.packt.animation.viewexample; import android.content.Context; import android.graphics.Canvas; import android.widget.TextView; public class MyTextView extends TextView { public MyTextView(Context context) { super(context); Chapter 1 [ 25 ] } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); } } Here we have subclassed the TextView class, but we haven't changed any behavior in it. We have overridden some of the Java methods in order to make it easy to interrupt the flow of the program and see how it is working. 8. You will see that there are some super() method calls in the generated code. Left-click in the margin next to each one, and select Toggle Breakpoint, so that there is a breakpoint next to each of them. 9. Next, edit ViewExample.java (also in com.packt.animation.viewexample) so that it is using MyTextView instead of TextView. It should look like the following block of code: package com.packt.animation.viewexample; import android.app.Activity; import android.os.Bundle; public class ViewExample extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyTextView helloView = new MyTextView(this); helloView.setText("Hello Views!"); setContentView(helloView); } } Here we are simply calling our new MyTextView, instead of the one that is used in the default Hello Android application. Animation Techniques on Android [ 26 ] 10. Navigate to Debug, in the Run menu, to debug this application in an emulator or an attached device. As it loads, you will see that it calls all of the methods, which we have break-pointed. ‰‰ It calls onMeasure to evaluate how much space it needs to allow MyTextView on the screen ‰‰ It calls onLayout to tell the widget how much space it has been allocated and to place the widget onto a specific location on the screen ‰‰ It calls onDraw last to actually place text on screen 11. Try rotating the device, or changing the orientation of the emulator, by holding down the Ctrl key and pressing F11, and watching it go through the layout process again. What just happened? You've seen just a snippet of the useful features that the views system provides. This is just for one simple widget; you can imagine how much work Android does when there is a more complex form element like a ListView on the screen. By using widgets, you don't have to worry about what happens when you rotate your screen. Widgets also handle interaction for you, and they provide features such as cursor navigation where you can use a directional joypad to navigate the screen rather than a touch screen. Chapter 1 [ 27 ] You've also seen that there are a lot of optional features that you can use, if you wish. If you use a surface, you will still need to provide a basic set of layout and drawing operations in order for your animations to appear onscreen, but you can also consolidate your program logic. Instead of doing separate redraw and layout operations for each and every view, you can produce your own lightweight version. But remember that there is a cost; you will lose a lot of functionality that could be important to you. Only use a surface when you are sure that your animation will not be required to have features that a form would have, such as text input, or when you are prepared to write all the extra functionality yourself. In Chapter 7, 2D Graphics with Surfaces, you will learn a little more about this. Android does still give surface users access to some view elements through the SurfaceView class, but it is still very much up to you to handle basic interaction. Animating awesome 3D You can also animate three-dimensional graphics in Android. There is a selection of common routines that developers use when drawing 3D objects. So long as you understand, loosely, how they work, there's no need to get a degree in mathematics to use them. In Chapter 7, 2D Graphics with Surfaces, I will give you a few stock routines that can be used and combined to make elemental 3D scenes. I will show what works with surfaces and what works with views; in general, there is quite a lot you can do with both. The following screenshot is an example of three-dimensional cubes, with shaded sides and vanishing points: 3D is all about mathematics, but Android does give you a few tools to make it somewhat easier to get that elusive third dimension into your applications. In fact, you can get some cool 3D effects using the techniques I've already told you about. Animation Techniques on Android [ 28 ] It's not all about the mathematics though. As my old computer graphics lecturer once told me, "nobody cares if your 3D is realistic, as long as it looks good", or something like that. I was a student at the time and probably not paying very much attention, but that's beside the point. 3D is all about perception. Simple effects can give your animations the feeling of real depth, even better than a computed 3D world. Sometimes this is a preferable technique when writing applications that must run on slow Android devices. This becomes even more important for us, because animations need to be re-calculated regularly enough to look smooth. Also, a simpler pseudo-3D style provides a cleaner visual experience than what comes with true three-dimensional visualizations. For instance, all of the following can give a sensation of three-dimensional depth, without having to do very much math at all. ‹‹ Drop shadows ‹‹ Color and alpha changes ‹‹ Scale changes In the following screenshot, you can see a simple illustration of using drop shadows and scale to give a sense of depth, without all the complex messing around that true 3D techniques require: Want to go faster? Android supports a very fast 3D graphics system called Open Graphics Libary for Embedded Systems (OpenGL ES). When you see realistic 3D animations and games on Android, they are very likely to be using OpenGL ES. It is found on lots of operating systems, not just Android. It's maintained by the Khronos group, and has been available on Android since version 2.0 (Eclair). Chapter 1 [ 29 ] Another, very fast way to generate complex graphics is to use native code, written in C or C++ programming languages. Native code can be faster than Java, because you can hand- optimize your code to make it faster. The Android Native Development Kit (NDK) supports this approach and can even be combined with OpenGL ES. Unfortunately, learning how to use OpenGL ES would require too much theory to fit into a beginner's book, and learning C++ would take even longer still. However, once you have mastered the basics of animation on Android, you may want to consider this route to get fast, realistic animation into your application. Have a go hero – what is right for your application This section is for anyone who has an application right now that they want to add a bit of animated juice to, and for anyone who's planning on creating an application. Grab some paper, as this is going to be the planning stage where you can plan out the animations for your interface. You can refer to this section whenever you have an application that you think needs a little animated zest! If you don't have any applications in mind right now, but you still want to be a hero, think of an application you feel would be cool to make. 1. Write down what the application does, and what concepts it involves. For instance, if you had an application that displays tide times for the local beach, the concepts might have been sea, tides, and scheduling. 2. Imagine how you'd expect a user to interact with your application. Get some ideas about what screens they might see. 3. Draw a screen from this application, as it would appear to the user. 4. Annotate each part of the screen that might have an animated component, saying what it is. Think about the concepts you wrote down in point 1, and how the animation is reflective of this. For instance, in the tide times application, it might be cool to have animations appear in waves. 5. Pick one of the animated components you made; we'll think about how we'll draw it next. 6. Would you want the animation to be pre-made with an image editor and drawn on the screen? If so, it sounds like you could use a frame animation. 7. Do you want to fade between two Drawable elements? A transition drawable is for you! 8. Would you want the animation to take place amongst the views and widgets on screen? Perhaps you could make use of a tween or an animator. Animation Techniques on Android [ 30 ] 9. Do y ou need to do something that isn't really provided by the ordinary Android view system that suits vector drawing or high performance? Time for a surface-based animation. 10. Go back to point 3 and think about another animation that you might use in your application. Repeat until you're so excited that you just have to start coding. 11. Bonus question: Will it look exciting or will it just confuse the user? With any luck, you've got a list of ideas to add animations to your application, and also what kind of technology it uses. The upshot of which is that you'll know exactly what you need to read next in order to perfect your application. The chapters are self-contained, so you can skip ahead, if you want to get stuck in! (However, if you want to take the traditional journey from beginning to end, that's fine by me.) Making a better application Remember who the audience for your application is and choose something that will satisfy them. I'll give you a load of good tips and advice in Chapter 9, Good Practice and Style, but here are couple of tips to get you started. Always be helpful It is all too easy to get carried away with lots of flashy graphics that only make your application more confusing. It is your responsibility whenever you give information to a user to draw their attention to the part that is most important. If there is a dancing amphibian (to pick an example at random) in one corner of the screen, they might not pay enough attention to whatever it is that you actually want them to notice. On the other hand, if the important data is presented with a bit of animated excitement, it will be impossible for them to miss it. Small and powered by batteries Throughout this book, it is worth remembering that you are writing for an operating system that is designed to be embedded in small, battery-powered devices. By allowing you to extend your information visualizations into the fourth dimension, animation can allow you to make more efficient use of a small screen. But animations are more power-hungry than other visual elements, and too much will flatten your user's battery. We will discuss this in detail in Chapter 9, Good Practice and Style. However, as a general guide, remember that fast graphics routines are also efficient in terms of power. Chapter 1 [ 31 ] Pop quiz – putting it all together 1. Which of these gives an animation a 3D feel? a A slow transition between two frames b A change in scale c A shift from red to blue 2. How can you draw several objects straight to the screen without declaring views? a Use an animator b Use an interpolator c Use a surface 3. Which of the following manipulates views to make an animation? a An animator b A surface c OpenGL ES 4. Why would you want to use a surface? a For maximum performance and flexibility b To get more colors c To fade between two frames 5. Adding lots of animations is… a Always good b Good for battery life c Only useful if they improve user experience 6. You want to animate one of Android's built-in widgets on a loop, which is most likely to be the right thing to do? a Put an animator on the parameters to animate b Re-implement the widget using a surface c Use a tween and keep restarting it when it finishes Animation Techniques on Android [ 32 ] Summary Now you know a little bit more about how the Android animation systems work, on their own as well as together in an application. You've seen how: ‹‹ A frame animation can be used to display animations composed of several pre-prepared frames and that its strength is its simplicity ‹‹ A transition is a simple fade between two animations ‹‹ Tweens bring motion to humdrum old form interfaces, explaining highlighting and events to make interaction intuitive and fun ‹‹ Animators let you animate a view, or any other compatible object, by making continuous modifications to its display parameters ‹‹ Surfaces allow you to strip away the ordinary Android display features, and get a bare-bones engine to show fast, efficient animations ‹‹ View-based animations are integrated more with the core functionality of Android, such as rotating screens and widget-based displays; surfaces are faster than views because they don't do any of this. ‹‹ Although OpenGL 3D is fast and flashy, you can create a lot of 3D graphics with a simple surface and some mathematics. In the next chapter, we will learn about frame-based animations and create some frame animations of our own! 2Frame Animations Frame animations build up animation from a series of still images that are shown in rapid succession, like a film reel. Each frame in a frame animation is shown for a fraction of a second and then it moves on to the next frame, giving an impression of motion like a film reel, as in the following graphic: In this chapter, we shall: ‹‹ Make a frame animation in XML ‹‹ Use Java to change a frame animation ‹‹ Make a transition animation, a simpler relative of frame animation A few sections of this will seem like revision if you are already comfortable with the Android views system, but for the most part I'll assume you are already comfortable with it. Ready? Let's go… Frame Animations [ 34 ] Making a frame animation First up, let's make a small activity which will run our first frame animation. Like a lot of graphical components in Android, we can use XML to define it. In fact, for this simple activity, we don't need to write any Java at all. Remember, a frame animation works by taking a series of still images and displaying them in a particular order. When making frame animations, the still images that you use will usually be numbered, so that you can tell which order to display them in. Time for action – the funky stick man In a recent survey of Android users, 90 percent of those who were asked said that they were very happy with the Android platform except for the fact that their phone did not contain an animation of a dancing stick man. Right now, we are going to make this killer app, using a stick figure prepared by the legendary stick figure artist Alexandro Del Shaw. 1. Create a new Android project with the following settings: ‰‰ Project name: Funky Stick Man ‰‰ Build Target: Android 3.0 ‰‰ Application name: Funky Stick Man ‰‰ Package name: com.packt.animation.funky ‰‰ Create Activity: FunkyActivity 2. Now, let's get some Drawables to work with. Drawable is a generic interface for anything on Android that is used for drawing graphics to the screen. In this case we will be using PNG images. Copy the res/drawable-*/ directories from the code bundle for this chapter. You'll find a ZIP file called tutorial_images_1. Unzip it somewhere local to copy it to your new project. ‰‰ In Eclipse, right-click on the res/ folder and select Import… ‰‰ Pick the option to import by File System, then click Next ‰‰ Navigate to the 5283_examples directory ‰‰ Import the Drawables to the res/drawable-hdpi, res/drawable-mdpi, and res/drawable-ldpi folders in your project. 3. Create the folder anim/ inside the res/ folder. Chapter 2 [ 35 ] 4. In the anim/ folder, create a new XML file called stickman.xml. 5. Create the root XML node in the file, so that it looks like the following: This is the standard root node for a frame animation. The android:oneshot attribute says whether to stop playing the animation after its first iteration. If false, it loops back to the beginning and plays indefinitely. We want the little fellow to keep dancing, so we choose false. 6. Take a look at the res/drawable-hdpi directory and observe the numbered animation frames: ‰‰ stickman_frame_01.png ‰‰ stickman_frame_02.png (In fact, the res/drawable-mdpi and res/drawable-ldpi folders contain the same images in different resolutions.) 7. For each frame, add an tag in numeric order to the stickman.xml, as in the following: The android:drawables are obviously the images in the res/drawable-* directories. The android:duration attribute is simply the number of milliseconds that each will be shown before the animation moves on to the next . There! You have finished your animation! Frame Animations [ 36 ] 8. Now for the final task, to display it to the user. Open up res/layout/main.xml and change the XML, so that it points to our new animation rather than the boring old "Hello Android!" text. 9. At this point, build and run your animation. If you've typed everything in as described it, you will see a stick figure, but he will not be animated. You have made your animation, and now it is time for you to get Android to play it, when the application loads. 10. Navigate your way to the Activity class in src/com/packt/animation/funky/ FunkyStickMan.java. We're going to add some code to it. I'll highlight the code that you need to add and break it down, so that we can look at it one piece at a time. 11. Firstly, let's add the classes we're going to be working with. I'll describe them briefly here. You will see how they are used shortly. package com.packt.animation.funky; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.widget.ImageView; import android.os.Bundle; AnimationDrawable is Android's Java representation of the animation-list that we created in step 3. ImageView will be used solely so that we can access the AnimationDrawable stored within the ImageView in main.xml. The next step will be to retrieve the AnimationDrawable that we added in the main.xml layout. We will access it through the onCreate() method in FunkyActivity, so that we start the animation as soon as the application Chapter 2 [ 37 ] is loaded. public class FunkyActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView animImage = (ImageView) findViewById(R.id.stickman); final AnimationDrawable animDrawable = (AnimationDrawable) animImage.getDrawable(); The previous code should look familiar if you have done any serious work with views before. Firstly, the content view, which is the main view that gets displayed on the screen, is added by setContentView. We pass in the resource ID that relates to the main.xml file we've just edited, so we know that it will contain the graphics we just added. FindViewById gets the container ImageView. From there we call getDrawable() to get the actual animation. We will assign it to a final object called animDrawable, because we're going to need it in an anonymous Runnable in just a second. 12. Sorry to interrupt, the source code for onCreate continues as follows: animImage.post( new Runnable() { public void run() { animDrawable.start(); } } ); } } 13. And here is where we actually start the animation. The call to animDrawable. start() is where we start the animation running. Why did we not just call the animDrawable.start() method from the onCreate() method? You must make the animDrawable.start() call from inside a method that will be called from the GUI thread. In this example, we use a .post(Runnable r) method to do exactly that. Frame Animations [ 38 ] 14. Let's build and run the new activity again. Before, the stick man was not moving at all, but now he should be dancing. Watch the little fellow go! What just happened? Here we made a purely graphical application based around a single animation, with very little programming needed. The Android XML resource system took care of all the hard work for us. The anatomy of a frame animation Look at the structure of the XML in stickman.xml. If you ignore the root node and concentrate on the items, then it is simply a list of things to show in the order that you want to show them. It's just like a program! And, just like a program, if you change the order of declaration, then the things will be shown in a different order too. Animation XML files are kept in res/anim as opposed to res/drawable, but the objects that the Android build tools will make will still be a subclass of Drawable. XML elements Here is a quick reference to the XML elements we use to create animations. The main headings are tags, and the subheadings are attributes of those tags. Chapter 2 [ 39 ] is always the top-level element in a frame animation. The animation- list is an ordered container of Drawable items. This tag should contain the following options: xmlns:android All top-level Android XML elements declare their namespace as xmlns: android="http://schemas.android.com/apk/res/android" android:oneshot oneshot is a Boolean flag to specify whether to stop after the first playback iteration or to keep on looping the animation. Each frame in the list is described as an item that references a pre-compiled Drawable. Each item should specify these attributes: android:drawable The android:drawable defines a reference to a Drawable using Android's usual resource hierarchy, that is, if your Drawables are in res/drawable or res/drawable-?dpi, you would use @drawable/your_drawable_name. It has to be specified. android:duration Specifies how long to show this item for. The value is given as an integer number in terms of milliseconds. Frame Animations [ 40 ] Timing Of course, in addition to determinig which image to show next, the tags also determine how long the image is shown, in milliseconds. Traditionally, movies are shown at 24 frames per second, because at that speed, most people cannot see any flickering or visual glitches. On a mobile device, you can get away with far fewer frames - around, around 12 frames per second still looks nice and smooth. Substituting the value 12 for the frames per second gives us: This is why the duration values are all set to 83 in the time for action section. For a smooth animation, you could use anything between 30 and 100 milliseconds per frame. The advantage of a small number is that it really displays smoothly. Larger delays might look jerky for some graphics. The advantages of a larger delay are that it makes the user's device work less than an animation with short delays, saving valuable battery life. It will also take up less space in the target device's memory as it requires fewer frames to be stored. It also allows the guy who makes your animations to work a little less, as he doesn't have to make as many pictures! You can also reduce unnecessary updates by putting a long delay on some frames, rather than animating several frames where nothing much is happening. There is no need for all of your frames to have the same duration. Images and Drawables This animation was constructed from pre-drawn PNG images of a stick man, which were added to the Android project in the same manner that you would add any image resource. It is important when using graphics like this that you ensure that the source Drawables are all the same size. This is common sense when you think about it; each image has to take up the same amount of screen space as the one before it, in order to maintain the illusion that it is just one moving image. Failure to do this may result in ugly animations that have flickering edges. The elements in the animation list refer to a set of Drawables that can be located by Android at compile time. While we did use a lot of PNG images, we didn't in fact, need to do so. Android would be just as happy if we had used any other sort of Drawable type. Chapter 2 [ 41 ] Screen size Different Android devices come in different sizes, and you may have to provide graphical elements that work on a whole range of different screens. Because the frame animation makes use of the Drawable class, we are immediately able to take advantage of the portability features that Drawables provide. In this particular example, we used the de-facto Android way to show images of different sizes, which is to say that we provided HDPI, MDPI, and LDPI versions of all the PNG images. If a user has a small screen, then the LDPI graphics are used. If (like most Android 3.0 devices) the device has a large, high-resolution screen, then we want to increase the resolution of the image to take advantage of this fact. Sometimes you run out of memory If, like me, you like to have a few graphical elements on screen at once, you will occasionally discover that your little mobile phone is not quite as powerful as your desktop computer when it comes to showing animations. Sometimes, your application will crash instead of showing you the animation you ask it for. Check LogCat for error messages that look similar to this: java.lang.OutOfMemoryError : bitmap size exceeds VM budget When this happens, you will need to reduce either the size of your animation, the number of frames, or both. Fortunately, most Android 3.0 devices have a bit more memory than their Android 1 and 2 counterparts, but this still happens occasionally. LogCat is an Android debugging tool that shows debug messages from all parts of the Android system, including your application. You can use it by navigating to the LogCat tab in the DDMS view of Eclipse, or by typing adb logcat from the command line (see http://developer. android.com/guide/developing/tools/logcat.html for more information). Pop quiz – making frame animations 1. If y ou change the order of the elements in an animation, what happens? a. Not a lot b. The animation changes at random c. The animation changes, because the frames are shown in a new order Frame Animations [ 42 ] 2. A fr ame animation in XML has to be composed of which of the following? a. PNG images b. Anything which Android can represent as a Drawable c. Animators 3. You will find XML for animation declared in which folder? a. res/Drawable b. res/anim c. src/Drawable 4. Which of the following sentences is not true? a. All android:duration values in an animation have to be the same b. Animations with longer durations save battery life c. Animations with too long durations will look jerky 5. What is the top-level XML element that holds a list of animation frames called? a. android:animation-list b. android:frameList c. android:frames Have a go hero – improve your dancing Of course, our little man isn't exactly doing the most exciting dance. Following is a choreographed dance that he can do to look a bit funkier: 1. Dance to the left three times 2. Do a jump 3. Dance to the right once 4. Pause for a second 5. Do a jump Guess what? It's your job to help him learn it, or rather, it's your job to program him to do it. Think you know what to do? You only need to make changes to the contents of stickman. xml. Here are some tips: ‹‹ Copying and pasting a block of elements will cause that section of the animation to be replayed. Chapter 2 [ 43 ] ‹‹ Each dance move is exactly a second long, and aligned to the start of the animation image list. If you know how many frames there are in a second (read Timing again if you've forgotten), you can easily divide the animation into the chunks that you need. Making frame animations in Java XML animations are defined at build time, but what if you want to make an animation that is defined or modified at runtime? We want to be able to change the animation by changing the animation sequence that is playing at any particular time. As you have learned from the Have A Go Hero – improve your dancing section, you can affect all manner of changes to the character of an animation, just by moving a few frames around. You can use Java in your application to add dynamic changes to the animation, by directly manipulating the AnimationDrawable that defines the frame animation. Time for action – making the stick man interactive Our little man looks a bit lonely dancing by himself, doesn't he? Wouldn't it be nice if you could join in with the dancing? In this section, we will add buttons to the animation, to allow a user to change the dance moves that the stick man is doing. In order to make the animation interactive, you're going to have to take the existing animation and split it up into its individual dance moves. There's a trick here: each dance move is exactly a second long. That means that the first 12 frames are the dance-left animation, the second 12 frames are the dance-right animation, and the final 12 define the jump animation. Frame Animations [ 44 ] We will make two new animations from the existing animation, one for dancing left and one for dancing right. The user interactions will be handled by changing which animation we are showing to the user. Sounds simple? Let's go! 1. Open up the Funky Stick Man project you made in the first part of this chapter. Did you skip through to this part without doing the first? Well, if you think you're ready for it, you can find the first part already done in the code bundle. Unzip the project 5283_2_example1 from the code bundle for this chapter. Open it as you would normally open an Android project. 2. Open up res/layout/main.xml and add the following new buttons underneath the ImageView containing our stick man: