medo medo - 5 months ago 40
Android Question

Animate margin change

I use this code for animate view in android its work perfect
problem when I set margin to zero or margin less the current margin its doesn't animate

the code

int margin = 100;


ValueAnimator varl = ValueAnimator.ofInt(margin);
varl.setDuration(200);
varl.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

@Override
public void onAnimationUpdate(ValueAnimator animation) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) myView.getLayoutParams();
lp.setMargins((Integer) animation.getAnimatedValue(), 0, 0, 0);
myView.setLayoutParams(lp);
}
});
varl.start();


Now set margin to 100 its animate but whenI want to set it to zero its set margin without animation

int margin = 0;



ValueAnimator varl = ValueAnimator.ofInt(margin);
varl.setDuration(200);
varl.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

@Override
public void onAnimationUpdate(ValueAnimator animation) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) myView.getLayoutParams();
lp.setMargins((Integer) animation.getAnimatedValue(), 0, 0, 0);
myView.setLayoutParams(lp);
}
});
varl.start();

Answer

The problem is that you didn't use the ValueAnimator.ofInt(int... values); correctly: you should explicitly tell the animator from which to which value it should animate. So, for example, you should animate from the current value to the wanted value. If your previous value, was, for example, 50, then the statement should be like this:

ValueAnimator varl = ValueAnimator.ofInt(50, margin);