Keep animated View at final Animation Position

后端 未结 3 2009
梦毁少年i
梦毁少年i 2020-12-14 08:10

So I\'m animating a view using animation:




        
3条回答
  •  臣服心动
    2020-12-14 08:50

    Please consider setFillAfter(boolean); setting it to true will make the view stay at the animated position.

    Animation anim = new TranslateAnimation(0, 0, 0, 100);
    
    // or like this
    Animation anim = AnimationUtils.loadAnimation(this, R.anim.animation_name);
    
    anim.setFillAfter(true); 
    anim.setDuration(1000);
    

    This can be done even easier using the ViewPropertyAnimator, available from API 14 and onwards:

    int animationpos = 500;
    View.animate().y(animationpos).setDuration(1000); // this will also keep the view at the animated position
    

    Or consider an AnimationListener to get the LayoutParams exactly after the animation:

    anim.setAnimationListener(new AnimationListener() {
    
                @Override
                public void onAnimationStart(Animation animation) {}
    
                @Override
                public void onAnimationRepeat(Animation animation) {}
    
                @Override
                public void onAnimationEnd(Animation animation) {
                      // get layoutparams here and set it in this example your views 
                      // parent is a relative layout, please change that to your desires
    
                      RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) View.getLayoutParams();
                      lp.topMargin = yournewtopmargin // use topmargin for the y-property, left margin for the x-property of your view
                      View.setLayoutParams(lp);
                    }
                });
    
        View.startAnimation(anim);
    

    UPDATE:

    How to know how many pixels the view moved, depending on the percentage values of the animation?

    The percentage value in your .xml animation is relative to the animated View's dimensions (such as width and height). Therefore, you just need to use your View's width and height properties (depending on weather u use x or y animation to get the actual animation distance in pixels).

    For example:

    Your View has a width of 400 pixels. Your animation animates the x-property from 0% to 75%, meaning that your view will move 300 pixels (400 * 0.75) to the right side. So onAnimationEnd(), set the LayoutParams.leftMargin to 300 and your View will have the desired position.

提交回复
热议问题