13

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);
Tevin J
  • 641
  • 2
  • 11
  • 15

3 Answers3

57

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();
Amit Yadav
  • 32,664
  • 6
  • 42
  • 57
3

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);
sddamico
  • 2,130
  • 16
  • 13
  • I tried this implementation before but it still resulted is a similar graphic glitch. However, I found a way to fix it. I called `.clearAnimation()` on the animated view before I set the padding. I assumed the code in the `.onAnimationEnd()` ran after the animation had ended. That doesn't seem to be the case. – Tevin J Aug 22 '13 at 16:47
  • In addition I removed `.setFillAfter()`. – Tevin J Aug 22 '13 at 18:06
2

Here is how to animate setPadding in Kotlin:

private fun setPaddingWithAnimation() {

    val paddingDp: Int = 20

    val density: Float = requireActivity().getResources().getDisplayMetrics().density

    val paddingPixel: Int = (paddingDp * density).toInt()

    val animator = ValueAnimator.ofInt(recyclerItems.paddingRight, paddingPixel)

    animator.addUpdateListener { valueAnimator -> binding.recyclerHealthTips.recyclerHealthTips.setPadding(
                paddingPixel, 0, valueAnimator.animatedValue as Int, 0) }
        
    animator.duration = 500
    animator.start()
}
Osama Remlawi
  • 2,356
  • 20
  • 21