How to move a view to another view using animation in Android?

后端 未结 2 1076
粉色の甜心
粉色の甜心 2021-01-14 09:14

I have a circle at the center of the screen inside which there\'s an ImageView + TextView. I have another two ImageView+TextView

相关标签:
2条回答
  • 2021-01-14 09:50

    I had the same issue and I fixed by using the next code (sorry is in Kotlin, but works the same in Java).Let's say viewFirst wants to reach viewTwo position:

    (DON'T USE):

                   viewFirst.animate()
                            .translationX(viewSecond.x)
                            .translationY(viewSecond.y)
                            .setDuration(1000)
                            .withEndAction {
                            //to make sure that it arrives, 
                            //but not needed actually these two lines
                                viewFirst.x = viewSecond.x
                                viewFirst.y = viewSecond.y
                            }
                            .start()
    

    (USE THIS SOLUTION):

                   viewFirst.animate()
                            .x(viewSecond.x)
                            .y(viewSecond.y)
                            .setDuration(1000)
                            .withEndAction {
                            //to make sure that it arrives, 
                            //but not needed actually these two lines
                                viewFirst.x = viewSecond.x
                                viewFirst.y = viewSecond.y
                            }
                            .start()
    
    0 讨论(0)
  • 2021-01-14 09:50

    Using the getX() and getY() methods define the position of the view in pixels, but the constructor you use defines Float type values that must be values from 0.0f to 1.0f

    TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)

    This is another option using the view`s position in pixels:

    viewFirst.animate()
            .x(viewSecond.getX())
            .y(viewSecond.getY())
            .setDuration(1000).withEndAction(new Runnable() {
        @Override
        public void run() {
            viewFirst.setX(tv2.getX());
            viewFirst.setY(tv2.getY());
        }
    }).start();
    
    0 讨论(0)
提交回复
热议问题