An Alpha Animation is animation that controls the alpha level of an object, i.e. fading it in and out. In Android, you can apply that fading effect to almost anything, from simple text, to images, buttons, check boxes, etc… Android has a few classes that can help you add that special effect to your programs, like AlphaAnimation andAnimationUtils.
Here’s an example on how to apply fading on any Android component subclass of View.
First, the XML resource. In the resources folder, we will create a tiny XML configuration file with the characteristics of the fading effect we want in an “anim” subfolder. So, under res/anim, here’s our alpha.xml:
1
2
3
4
5
| <? xml version = "1.0" encoding = "utf-8" ?> android:fromAlpha = "0.0" android:toAlpha = "1.0" android:duration = "1000" /> |
We are choosing to have a very basic full fade in effect (alpha from 0 to 1) that lasts one second. The above can also be done directly in Java code:
1
2
| Animation animation = new AlphaAnimation( 0 .0f, 1 .0f); animation.setDuration( 1000 ); |
Configuring the animation in resources or in code is ultimately a matter of preference. We will use the XML in this example. This is our class that does the above fading to any View (TextView, Button, etc..):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| package com.ts.fx.utils; import android.app.Activity; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; public class Fader { /** * handles all subclasses of View : TextView, Button, ImageView etc.. * given the component's id in their layout file * */ public static void runAlphaAnimation(Activity act, int viewId) { // load animation XML resource under res/anim Animation animation = AnimationUtils.loadAnimation(act, R.anim.alpha); if (animation == null ){ return ; // here, we don't care } // reset initialization state animation.reset(); // find View by its id attribute in the XML View v = act.findViewById(viewId); // cancel any pending animation and start this one if (v != null ){ v.clearAnimation(); v.startAnimation(animation); } } } |
The runAlphaAnimation() method takes an Activity reference and a View id attribute (as set up in the View’s layout XML). We’re basically done. all we have to do now is call it from any one of our Activitites:
1
2
3
4
5
| // inside an Activity with text, checkbox and button Fader.runAlphaAnimation( this , a_text.getId()); Fader.runAlphaAnimation( this , a_checkbox.getId()); Fader.runAlphaAnimation( this , a_button.getId()); //etc... |
That’s all there is to it. The same basic technique seen here applies to all other special effects like translating, scaling or rotating components. The Animation classes have of course lots of other cool stuff, like controlling the z-ordering of the animated components, acceleration and repeat effects.
No comments:
Post a Comment