medo
medo

Reputation: 479

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 when I set margin to 100 it animates, but when I 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();

Upvotes: 5

Views: 6104

Answers (2)

Bartek Lipinski
Bartek Lipinski

Reputation: 31438

You can use my library for that:

ViewPropertyObjectAnimator.animate(myView).leftMargin(100).setDuration(200).start();

Upvotes: 4

Aleksandar Stefanović
Aleksandar Stefanović

Reputation: 1593

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

Upvotes: 5

Related Questions