th3ramr0d
th3ramr0d

Reputation: 484

TranslateAnimation not moving view to correct place

I have two ImageViews inside a constraint layout. One on top and one on bottom. I want to move the bottom one onto the top one. Of course I know it doesn't change it's actual position which I am ok with. When I use TranslateAnimation to move to the specified coordinates the image goes down and to the right instead of moving up and to the right. Also when it moves to the right it is slightly off. I can use view.animate().y(getTop).x(getLeft); and it moves the image into the correct position but then it is stuck there. I can't get it to move back to its original like it would if fillAfter was false.

First I get the destination location

float x = playerOneCard.getLeft();
float y = playerOneCard.getTop();

This code moves the card to the correct location but does not reset it after being moved. I need it to essentially move there, go back to it's original place, and repeat as many times as the button is pressed.

playerOneCardMove.animate().x(x).y(y);

This code moves the image but down and towards the right no where close to lining up with the desired destination.

TranslateAnimation translateAnimation = new 
TranslateAnimation(Animation.ABSOLUTE,x,Animation.ABSOLUTE,y);
translateAnimation.setDuration(500);
translateAnimation.setFillAfter(false);
playerOneCardMove.startAnimation(translateAnimation);

Upvotes: 0

Views: 131

Answers (1)

th3ramr0d
th3ramr0d

Reputation: 484

Figured it out. Since I was going from the absolute position of the first image the top left of that image is 0,0. So it was moving accordingly. Instead I measured the distance from the top of the image on the bottom to the top of the image above it and then moved it according to distance. I did the same for both x and y coordinates.

float distanceY = Math.abs(playerOneCardMove.getTop() - playerOneCard.getTop());
float distanceX = Math.abs(playerOneCard.getLeft() - playerOneCardMove.getLeft());
TranslateAnimation translateAnimation = new TranslateAnimation(Animation.ABSOLUTE,distanceX ,Animation.ABSOLUTE,(distanceY) - (distanceY*2));
translateAnimation.setDuration(1000);
translateAnimation.setFillAfter(false);
playerOneCardMove.startAnimation(translateAnimation);

Hope this helps someone else.

Upvotes: 0

Related Questions