You need to remember few things. If you want to use animating of the translation you need to provide the distance difference along both axis (x and y). So your code could look more less like this:
View viewToBeMoved = findViewById(R.id.view_to_be_moved);
View destinationView = findViewById(R.id.destination_view);
int xDiff = destinationView.getLeft() - viewToBeMoved.getLeft();
int yDiff = destinationView.getTop() - viewToBeMoved.getTop();
viewToBeMoved.animate().translationXBy(xDiff).translationYBy(yDiff);
Also you need to remember that this code will work ONLY when both viewToBeMoved
and destinationView
have the same parent (so getTop()
and getLeft()
methods return proper values).
Edit:
For views that dont belong to the same parent you can try something like this:
View viewToBeMoved = findViewById(R.id.view_to_be_moved);
int[] viewToBeMovedPos = new int[2];
viewToBeMoved.getLocationOnScreen(viewToBeMovedPos);
View destinationView = findViewById(R.id.destination_view);
int[] destinationViewPos = new int[2];
destinationView.getLocationOnScreen(destinationViewPos);
int xDiff = destinationViewPos[0] - viewToBeMovedPos[0];
int yDiff = destinationViewPos[1] - viewToBeMovedPos[1];
viewToBeMoved.animate().translationXBy(xDiff).translationYBy(yDiff);
instead of getLocationOnScreen
you can use getLocationInWindow
but in both cases be sure that you "invoke it AFTER layout has happened"