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));
punksta
  • 2,738
  • 3
  • 23
  • 41

2 Answers2

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); 
mouayad
  • 443
  • 3
  • 10
  • 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 up – Cristian Babarusi Feb 14 '17 at 19:04
  • *note:* views during initialization will return you position 0, try to perform this operation in `new Handler().postDelayed(new Runnable{}, 200);` – Kirill Karmazin Apr 02 '19 at 20:28
  • @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 }`. – Darwind Jun 24 '20 at 09:46
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()
}
Sachin Singh
  • 149
  • 1
  • 7