Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use setUpdateListener on api level lower than 19

For an animation i have to listen to every step of the ViewPropertyAnimator. I use the AnimatorUpdateListener in combination with the setUpdateListener.
source: http://developer.android.com/reference/android/view/ViewPropertyAnimator.html


Example how i use it:

image.animate().translationY(transY).setDuration(duration).setUpdateListener(new AnimatorUpdateListener() {

       @Override
       public void onAnimationUpdate(ValueAnimator animation) {
           // do my things
       }
});

Now im moving an object from A to B and have to detect some things while moving. Now setUpdateListener is really helpful with this, and with this code it all works. But its requires api level 19. I really want to use api level 14 for this project. Is there an alternative for setUpdateListener?

ViewPropertyAnimator.setUpdateListener

Call requires api level 19 (current min is 14)
like image 809
Dion Segijn Avatar asked Dec 03 '14 12:12

Dion Segijn


2 Answers

Below is an improvement of Zsolt's answer with the listener code in one place and a code-level check of the API version:

ValueAnimator.AnimatorUpdateListener updateListener = new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // do my things
    }     
};

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    image.animate()
          .translationY(transY)
          .setDuration(duration)
          .setUpdateListener(updateListener);
} else {

    ObjectAnimator oa = ObjectAnimator.ofFloat(image, View.TRANSLATION_Y, transY)
                                  .setDuration(duration);
    oa.addUpdateListener(updateListener);
    oa.start();
}
like image 176
John Cummings Avatar answered Oct 06 '22 18:10

John Cummings


With API level 19 or above you can say

image.animate()
     .translationY(transY)
     .setDuration(duration)
     .setUpdateListener(new AnimatorUpdateListener() {

         @Override
         public void onAnimationUpdate(ValueAnimator animation) {
             // do my things
         }

     });

With API level 11 or above you can resort to:

ObjectAnimator oa = ObjectAnimator.ofFloat(image, View.TRANSLATION_Y, transY)
                                  .setDuration(duration);
oa.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // do my things
    }
});
oa.start();

NOTE: While ViewProperyAnimator calls View.setHasTransientState() under the hood for the animated view, ObjectAnimator does not. This can result in different behavior when doing custom (i.e. not with ItemAnimator) RecyclerView item animations.

like image 41
Zsolt Safrany Avatar answered Oct 06 '22 18:10

Zsolt Safrany