Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 730
dusm Avatar asked Jan 08 '14 07:01

dusm


People also ask

How do you animate a view?

Create ImageView in the activity_main. xml along with buttons that will add animation to the view. Navigate to the app > res > layout > activity_main. xml.


1 Answers

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.

like image 163
Shirane85 Avatar answered Nov 07 '22 05:11

Shirane85