Home » Android » android – How do you animate a change in a view's padding?

android – How do you animate a change in a view's padding?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to animate the change in the padding of a view. The resting place of the translation animation is the same as the padding I want to apply.

TranslateAnimation moveleft = new TranslateAnimation(Animation.ABSOLUTE, 0.0f,
                    Animation.ABSOLUTE, PADDING, Animation.ABSOLUTE,
                    0.0f, Animation.ABSOLUTE, 0.0f);

moveLeft.setDuration(500);
moveLeft.setFillAfter(true);

This starts the view’s animation then sets the padding. This doesn’t exactly work because it cause a graphical glitch.

v.startAnimation(moveleft);   
v.setPadding(PADDING, 0, 0,0);
How to&Answers:

Instead of setting your padding right away, why not try an animation listener to set the padding after the animation has completed?

v.setAnimationListener(new Animation.AnimationListener() {
    ...
    @Override
    public void onAnimationEnd(){
        v.setPadding(PADDING, 0, 0,0);
    }
    ...
});
v.startAnimation(moveleft);

Answer:

Use ValueAnimator, its really simple and unclutter

say,
we have to change right padding to _20dp where as left, top and bottom padding are _6dp, _6dp and 0 respectively.

ofInt() is varagrs type. the value we have to animate is pass in it as KeyValue pair (arg1 = current value, arg2 = target value,…………)

Here we go,

ValueAnimator animator = ValueAnimator.ofInt(view.getPaddingRight(), _20dp);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator){
        view.setPadding(_6dp, _6dp, (Integer) valueAnimator.getAnimatedValue(), 0);
    }
});
animator.setDuration(200);
animator.start();