Wednesday 23 April 2014

Animating a ProgressBar to a specific value

In this tutorial I'll explain how to set a specific progress value to a ProgressBar using a smooth animation.



ObjectAnimator animation = ObjectAnimator.ofInt(pbBudget, "progress", 0, 50);
To begin with we create an ObjectAnimator object: this is a subclass of ValueAnimator that provides support for animating properties on target objects. The constructors of this class take parameters to define the target object that will be animated as well as the name of the property that will be animated. In this example we used the following parameters:
  • pbBudget: reference to the ProgressBar in the layout;
  • "progress": the name of the property to be animated;
  • 0: starting point of the animation;
  • 50: ending point of the animation.

animation.setDuration(1500);
The code is self-explanatory: the animation lasts 1,5 seconds.


animation.setInterpolator(new DecelerateInterpolator());
It is possible to use different interpolators for our animation, like for example:

animation.start();

You can also create an animation for the ProgressBar from scratch, using the method setProgress(int progress) with a delay (android.os.SystemClock.sleep(long ms)).
If you decide to do so, I suggest to use an AsyncTask and update the ProgressBar using the onProgressUpdate method.
Avoid animating the ProgressBar in the UI thread with a loop:
  1. because this will freeze the UI until the animation is completed;
  2. because even though you are in the UI thread, you don't release the UI thread until the animation is completed, thus preventing the system to update the UI (and the ProgressBar) itself.

4 comments:

  1. thanks alot from me too. It works like a charm

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Another tip: If the animation is not very smooth then you can multiply the max value and progress value with a certain (same) number. Multiplying and dividing by a number has mathematically no effect, but the code gets more digits to animate.

    ReplyDelete