android animation move view to another view
Asked Answered
T

2

10

I have two views in different layouts I want to move one to another. What's wrong with my code? Y animation plays wrong. First view is located in fragment's layout, second in status bar

    ...
    int p1[] = new int[2];
    int p2[] = new int[2];
    viewOne.getLocationInWindow(p1);
    viewTwo.getLocationInWindow(p2);


    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet
            .play(ObjectAnimator.ofFloat(expandedImageView, "X", p1[0], p2[0] - p1[0]))
            .with(ObjectAnimator.ofFloat(expandedImageView, "Y", p1[1], p2[1] - p1[1]))
            .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale))
            .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale));
Twopenny answered 2/12, 2014 at 13:22 Comment(3)
How does it play wrong?Spurgeon
@Spurgeon it should move to corner of the screen, but y does not growTwopenny
please see my answer, it's directly related: https://mcmap.net/q/131012/-how-to-move-a-view-to-another-view-using-animation-in-androidCason
S
28

I have a another solution for you:(move viewOne to viewTwo)

 TranslateAnimation animation = new TranslateAnimation(0, viewTwo.getX()-viewOne.getX(),0 , viewTwo.getY()-viewOne.getY());
    animation.setRepeatMode(0);
    animation.setDuration(3000);
    animation.setFillAfter(true);
    viewOne.startAnimation(animation); 
Sagunto answered 10/12, 2014 at 11:19 Comment(3)
sorry, i tried this code but is not working how is supose to do. i have an imageview and i want to move it to the other fixed image view but in fact is moving my image some way on diagonal side to the upWhitelaw
note: views during initialization will return you position 0, try to perform this operation in new Handler().postDelayed(new Runnable{}, 200);Gilreath
@KirillKarmazin alternatively to using a Handler you could also use the onGlobalLayoutListener on the viewTreeObserver, so that the above code is inside viewTwo.viewTreeObserver.addOnGlobalLayoutListener { // Animation code here }.Jacinto
C
1

Try this

private fun moveView(viewToBeMoved: View, targetView: View) {
    val targetX: Float =
        targetView.x + targetView.width / 2 - viewToBeMoved.width / 2
    val targetY: Float =
        targetView.y + targetView.height / 2 - viewToBeMoved.height / 2

    viewToBeMoved.animate()
        .x(targetX)
        .y(targetY)
        .setDuration(2000)
        .withEndAction {
            targetView.visibility = View.GONE
        }
        .start()
}
Creatine answered 22/1, 2022 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.