Tuesday, September 07, 2010

Android: Fading images and forcing them to stay that way

In my attempts at making the world best reverse calculator (in tight competition with the 100's of other developers doing the same thing on Market - talk about reinventing the wheel) I was considering how to visually best show the math concept subtraction.

After contemplating a bit I wanted to implement a small Packman eating the images representing operand2.

This would look something like

5 - 2 =

***** (packman eats the last 2 dots) and the result is ***

My initial though was to use animated gifs, but my findings (here amongst other places www.anddev.org) were that this was a non trivial exercise and that I really wanted to use something that was built in to Android.

Creating a new folder under the res folder in the Eclipse project named anim and placing a file named fadeout.xml with the following content

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="3000" android:repeatCount="0" />

allowed me to use the following code in my SubtractionProblem class

// Fade out all the imageviews that are representing operand2
for(View view : operand2Views){
 Animation myFadeOutAnimation = AnimationUtils.loadAnimation(view.getContext(), R.anim.fadeout);
 view.startAnimation(myFadeOutAnimation); //Set animation to your ImageView


This fades the operand2 images and the
myFadeOutAnimation.setFillAfter(true) code makes the images stay faded (otherwise Android will animate them and return the images to the original state)

No comments: