Android

Flash or Pulse Animation for a Button Android

At times we may require to get user’s attention to click on a Button, to view some important information in app. For this purpose Flash or Pulse animation helps us very well. Below are code snippets to implement these animations.

Implementing Flash animation

We can use AnimationDrawable class, to add frames of two different colours, which produces flash animation. Below is an example code.

Here im displaying rounded shape button, so i used RoundRectShape class, given radii as argument. If you want a rectangle shape, just replace radii withnull

AnimationDrawable adBtn;

private void applyFlashBackgroundAnimation(){
     float[] radii = new float[8];
     radii[0] = getResources().getDimension(R.dimen.spacing_10);
     radii[1] = getResources().getDimension(R.dimen.spacing_10);
     radii[2] = getResources().getDimension(R.dimen.spacing_10);
     radii[3] = getResources().getDimension(R.dimen.spacing_10);

     radii[4] = getResources().getDimension(R.dimen.spacing_10);
     radii[5] = getResources().getDimension(R.dimen.spacing_10);
     radii[6] = getResources().getDimension(R.dimen.spacing_10);
     radii[7] = getResources().getDimension(R.dimen.spacing_10);
     ShapeDrawable selShape = new ShapeDrawable();
     selShape.setShape(new RoundRectShape(radii, null, null));
     selShape.getPaint().setColor(Color.GREEN);

     ShapeDrawable defShape = new ShapeDrawable();
     defShape.setShape(new RoundRectShape(radii, null, null));
     defShape.getPaint().setColor(Color.GRAY);
     
     adBtn = new AnimationDrawable();
     adBtn.addFrame(selShape, DELAY);
     adBtn.addFrame(defShape, DELAY);
     adBtn.setOneShot(false);
     btnObj.setBackgroundDrawable(adPick);//btnObj is your Button object
     Handler handler== new Handler();
     handler.postDelayed(new Runnable() {
         @Override
          public void run() {
              adBtn.start();
          }
     }, 100);
}

//To Stop Animation, simply use stop method of AnimationDrawable object as below.
private void stopFlashAnimation()
    adBtn.stop();
}

Implementing Pulse animation

To produce Pulse or Heartbeat animation, we use ObjectAnimator class. Below is the example code.

ObjectAnimator objAnim;
private void pulseAnimation(){
    objAnim= ObjectAnimator.ofPropertyValuesHolder(btnObj, PropertyValuesHolder.ofFloat("scaleX", 1.5f), PropertyValuesHolder.ofFloat("scaleY", 1.5f));
    objAnim.setDuration(300);
    objAnim.setRepeatCount(ObjectAnimator.INFINITE);
    objAnim.setRepeatMode(ObjectAnimator.REVERSE);
    objAnim.start();
}

//To Stop Animation, simply use cancel method of ObjectAnimator object as below.

private void stopPulseAnimation()
    objAnim.cancel();
}

That’s it for displaying Flash or Pulse animation for button.

Hope it helps somebody… 🙂

You may also interested in..

 

Leave a Reply

Your email address will not be published. Required fields are marked *