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);
}
});
}