App Layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dip"
android:src="@drawable/rhino" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dip"
android:text="Please click me" />
</LinearLayout>
Coding the animation
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class BlinkAnimation extends Animation {
/*...*/
private int totalBlinks;
private boolean finishOff;
public BlinkAnimation(int totalBlinks, boolean finishOff) {
this.totalBlinks = totalBlinks;
this.finishOff = finishOff;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float period = interpolatedTime * totalBlinks * 3.14f + (finishOff ?3.14f / 2 : 0);
t.setAlpha(Math.abs(FloatMath.cos(period)));
}
/*...*/
public boolean willChangeBounds() {
return false;
}
@Override
public boolean willChangeTransformationMatrix() {
return false;
}
Using the animation
private ImageView image;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image = (ImageView) findViewById(R.id.image);
((Button) findViewById(R.id.button)).setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
Animation animation;
if (image.getVisibility() == View.VISIBLE) {
animation = new BlinkAnimation(3, true);
animation.setInterpolator(new DecelerateInterpolator());
} else {
animation = new BlinkAnimation(3, false);
animation.setInterpolator(new AccelerateInterpolator());
}
animation.setDuration(1000L);
animation.setAnimationListener(this);
image.startAnimation(animation);
}
}
@Override
public void onAnimationEnd(Animation animation) {
image.setVisibility(image.getVisibility() == View.VISIBLE ?
View.INVISIBLE : View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
}