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:
- LinearInterpolator, where the rate of change is constant;
- DecelerateInterpolator, where the rate of change starts out quickly and and then decelerates;
- AccelerateInterpolator, where the rate of change starts out slowly and and then accelerates;
- OvershootInterpolator, where the change flings forward and overshoots the last value then comes back;
- etc... (for other interpolator check the interface android.view.animation.Interpolator).
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:
- because this will freeze the UI until the animation is completed;
- 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.
Thanks a lot for this.
ReplyDeletethanks alot from me too. It works like a charm
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteAnother 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