ValueAnimator

Animation in Android
Applying ValueAnimator we can animate any number of objects of any type at the same time using one instance of it. Also you can use not only the animated value but the fraction to be able to interpolate between other two values without creating a new instance of ValueAnimator. So great tool.

Usage:
Firstly we create an instance of ValueAnimator as

ValueAnimator animator =
     ValueAnimator.ofFloat(start value, end value);

Then we should add an update listener to it like below

animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
     float value = (float) animator.getAnimatedValue();
     //update your views here
     //do not forget to invalidate your views
   }
     });

Now we can set parameters of animator and start it in suitable place.

animator.setDuration(duration);
animator.start();

Note that we can play some animations together by creating an instance of AnimatorSet and using play() and with() functions. Also we can add an instance of AnimatorListener to provide proper functionality for events of the animation. See below example.
The following example shows how ValueAnimator is useful in animating several views each in several properties.
Example 1: Please create a new Android Studio project and use Empty template. Then edit the activity_main.xml (layout) file as shown below. Note that the background resource of buttons in this example is an SVG file which has been converted to ic_sun.xml file.


The MainActivity.java file is as follows.


And it is the result!


Example 2: Here we use a custom view (something like the custom view created in custom view) and make it to play a simple animation. Please create a new Android Studio project and use Empty template and refer to custom view for details of the custom view. We should create a new java file PieView.java shown below.


Then edit the activity_main.xml as below.


In the mainActivity.java one instance of ValueAnimator can simply do the animation properly.


Now the result is something like below.


Comments