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

Tevin J picture Tevin J · Aug 22, 2013 · Viewed 10.7k times · Source

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);

Answer

Amit Yadav picture Amit Yadav · Sep 28, 2014

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();