Problems with ObjectAnimator

0

I'm doing an animation where an image slides from the bottom up using ObjectAnimator. In the Android Studio emulator the animation occurs perfectly, but when I squeeze on Android devices (I tested it in more than two), the animation seems to jump.

Here is the code:

imgAnim = (ImageView) findViewById(R.id.imagem);
ob = ObjectAnimator.ofFloat(imgAnim, "y", height, 70);
ob.setDuration(2100);
ob.start();
    
asked by anonymous 07.07.2017 / 05:14

1 answer

0

The jump is due to the value of the height variable not being the value of the y position where ImageView is located.

When you start the animation, the image "jumps" from its position to the position height and only then the smooth movement between height and 70 is started.

To have no jump, height must have the y position value of ImageView:

height = imgAnim.getY();

Note:

The getY() method will return 0 if it is used in onCreate() , at that time the views have not yet been scaled or positioned.

If the code you posted is not in onCreate() is not even being called, change the line

ob = ObjectAnimator.ofFloat(imgAnim, "y", height, 70);

for

ob = ObjectAnimator.ofFloat(imgAnim, "y", imgAnim.getY(), 70);

If it is, you must ensure that it runs after the views have been scaled and positioned.

To do this, create a method to place the animation code:

private void animateImage(ImageView imageView, float startY, float endY){

    ObjectAnimator ob = ObjectAnimator.ofFloat(imageView, "y", startY, endY);
    ob.setDuration(2100);
    ob.start();
}

In the onCreate() method, add an OnGlobalLayoutListener to the ImageView and call the animateImage() method in the onGlobalLayout() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ....
    ....
    imgAnim = (ImageView) findViewById(R.id.imagem);
    imgAnim.getViewTreeObserver().addOnGlobalLayoutListener(new 

        ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                //Remove o listenner para não ser novamente chamado.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    imgAnim.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    //noinspection deprecation
                    imgAnim.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }

                //Aqui a ImageView já foi dimensionada e posicionada
                //inicia a animação
                animateImage(imgAnim, imgAnim.getY(), 70);
            }
        });
}
    
07.07.2017 / 11:01