I've written a custom View
. Now I want to do a little custom animation when the user touches it.
When I say custom, I mean I basically want to render each frame myself, and not use a "predefined" animation like described here.
What is the proper way of implementing this?
Most flexible (and pretty easy) way to create custom animation is to extend
Animation
class.In general:
setDuration()
method.setInterpolator()
(for exapmle you can useLinearInterpolator
orAccelerateInterpolator
etc.)applyTransformation
method. Here we interested ininterpolatedTime
variable which changes between 0.0 and 1.0 and represent the your animation progress.Here is an example (I'm using this class to change ofsset of my
Bitmap
.Bitmap
itself is drawn indraw
method):Also you can modify
View
by usingTransformation#getMatrix()
.UPDATE
In case if you're using Android Animator framework (or compatibility implementation -
NineOldAndroids
) you can just declare setter and getter for your customView
property and animate it directly. Here is an another example:This is the code that I use to produce a custom, frame-by-frame animation in my onCreate().
After that I need to start the animation, but must do so inside the UI thread. Therefore I make use of Runnable.
I start that Runnable from an onClick() using the .post() method of ImageView:
There are four types of animation that you can add to your custom view.
Here is a blog post which explains each one of them in detail.
Once you are done with creating an animation, just use the below code to add that custom animation to the view.
I assume you create each frame as a bitmap, and then pass it to the Animation directly, instead of getting the Drawable from resource.
In addition to defining tweened animations in XML you can also define frame-by-frame animations (stored in res/drawable).
Set the animation as the View background via setBackgroundResource.
If you're looking to do something more complicated, take a look at the Canvas class. See the brief intro on how to draw with Canvas.