Move an ImageView to different position in Animated way in Android

后端 未结 4 566
轻奢々
轻奢々 2020-12-04 17:00

I have several ImageViews in a RelativeLayout. now, when user taps any of the ImageView, I want it to be moved to a specified location with subtle

4条回答
  •  温柔的废话
    2020-12-04 17:31

    TranslateAnimation animation = new TranslateAnimation(0, 50, 0, 100);
    animation.setDuration(1000);
    animation.setFillAfter(false);
    animation.setAnimationListener(new MyAnimationListener());
    
    imageView.startAnimation(animation);
    

    UPDATE : The problem is that the View is actually still in it's old position. So we have to move it when the animation is finished. To detect when the animation is finished we have to create our own animationListener (inside our activity class):

    private class MyAnimationListener implements AnimationListener{
    
        @Override
        public void onAnimationEnd(Animation animation) {
            imageView.clearAnimation();
            LayoutParams lp = new LayoutParams(imageView.getWidth(), imageView.getHeight());
            lp.setMargins(50, 100, 0, 0);
            imageView.setLayoutParams(lp);
        }
    
        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    
        @Override
        public void onAnimationStart(Animation animation) {
        }
    
    }
    

    So the onClickEvent will get fired again at it's new place. The animation will now move it even more down, so you might want to save the x and y in a variable, so that in the onAnimationEnd() you move it not to a fix location.

提交回复
热议问题