ObjectAnimator vs TranslateAnimation

2019-02-22 05:51发布

问题:

I just do a simple project where I try to show/hide a layout on the top of a LinearLayout with TranslateAnimation. There was a flicker because when I call onAnimationEnd(), the animation wasn't finished for 0.1sec.

Example:

            @Override
            public void onAnimationEnd(Animation animation) {
                retractableLayout.setVisibility(View.GONE);
            }

When I search on stackoverflow, I found there's another way to do it. With ObjectAnimator. After using it, my animation was fine without a View.GONE

What is the difference between TranslateAnimation and ObjectAnimator? Is one of them is deprecated and they do the same thing or there's a time when one or the other is better.

Here's a github repo with the 2 versions (https://github.com/charlesvigneault/AAA_Test1)

Thanks

回答1:

The difference is mainly that if you use a TranslateAnimation, the view which you are animating does not really leave its original position on the screen, it just makes it look like it is moving. So the view basically doesnt change its coordinates.

Check this video about View Animations : https://www.youtube.com/watch?v=_UWXqFBF86U

If you use an ObjectAnimator the view really changes its actual position.

TranslateAnimation is not deprecated, you can still find it on Lollipop, but for most cases I can recommend a class called ViewPropertyAnimator , which many people still dont seem to know about, it is probably the easiest and most straight forward way to animate a view, and can also save you a lot of code. Heres an example :

retractableLayout.animate()
                .translationX(toX)
                .translationY(toY)
                .setDuration(duration)
                .setInterpolator(interpolator)
                .setStartDelay(startDelay);

You can also set a listener etc., be sure to check the available methods.

And check out this really helpful video :

https://www.youtube.com/watch?v=3UbJhmkeSig



回答2:

TranslateAnimation is depracated since android 3.0 and ObjectAnimator is the way to go. Object animator is much more flexible as it allows you to "animate" any object property that has proper setter and getter implemented. Check official android dev guide http://developer.android.com/guide/topics/graphics/overview.html