how to move view to the center of screen using animations in android

android, android-animation, android-relativelayout, android-view

Solution

Have you tried:

_buttonC.animate().translationX(parentCenterX - _buttonC.getWidth()/2).translationY(parentCenterY - _buttonC.getHeight()/2);

Of course you will have to calculate the parent centerX and centerY:

float parentCenterX = parent.getX() + parent.getWidth()/2;
float parentCenterY = parent.getY() + parent.getHeight()/2;

Hope this will help.

Problem

i'd like to move a view (in my case - a button, but it doesn't really matter) to the center of the screen. when i'm running the move without animations, it works. however, i'm having a hard time deciding which animations i should use to do so, since TranslateAnimation only lets me do so but specify the exact x,y coordinates, which i don't have (tried it with metrics, but the calculation didn't work, and i don't want to use this method). So, this code works without animations : ``` RelativeLayout.LayoutParams parms2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); parms2.addRule(RelativeLayout.CENTER_VERTICAL); parms2.addRule(RelativeLayout.CENTER_HORIZONTAL); _buttonC.setLayoutParams(parms2); ``` and when i try to add animations, it doesn't. ``` ObjectAnimator ani = ObjectAnimator.ofFloat(_buttonC, "Y", 2000); ani.setDuration(4000); ani.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { RelativeLayout.LayoutParams parms2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); parms2.addRule(RelativeLayout.CENTER_VERTICAL); parms2.addRule(RelativeLayout.CENTER_HORIZONTAL); _buttonC.setLayoutParams(parms2); } @Override public void onAnimationEnd(Animator animation) { } }); ``` any help will be greatly appreciated :)

Original source