Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 668
medo Avatar asked Mar 12 '23 20:03

medo


2 Answers

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

like image 55
Aleksandar Stefanović Avatar answered Mar 19 '23 19:03

Aleksandar Stefanović


You can use my library for that:

ViewPropertyObjectAnimator.animate(myView).leftMargin(100).setDuration(200).start();
like image 40
Bartek Lipinski Avatar answered Mar 19 '23 18:03

Bartek Lipinski