shubendrak
shubendrak

Reputation: 2068

Animating Margin by ValueAnimator vs ViewPropertyAnimator translationX

I am a beginner in android animation. I have few views inside a RelativeLayout and i wish to change view position. What are the options i have and how they differ?

I have tried following:

view.animate()
.translationX(toX)
.setDuration(duration);

and

RelativeLayout.MarginLayoutParams params = (RelativeLayout.MarginLayoutParams) view.getLayoutParams();
ValueAnimator animator = ValueAnimator.ofInt(params.rightMargin, 100);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator) {
        params5.rightMargin = (Integer) valueAnimator.getAnimatedValue();
    }
});

Both changes the position of the view. Can anyone explain me the difference in these two method. What other options i have and which is the preferred option.

Upvotes: 1

Views: 957

Answers (2)

Gabor Novak
Gabor Novak

Reputation: 286

The first one is the best solution. It's specifically created for animations, so it's the most optimized version. You have to keep in mind that if you animate a view then the whole layout will be recalculated with each movement (obviously for the translation, but not for an alpha for example), so you have to keep the layout tree as flat as possible. If it's possible try to avoid the RelativeLayouts, since they are measured twice at each frame (https://youtu.be/HXQhu6qfTVU). You can check out a lot of cool videos here about the performance issues: https://www.youtube.com/watch?v=ORgucLTtTDI&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE

Upvotes: 1

Vitaly Zinchenko
Vitaly Zinchenko

Reputation: 4911

view.animate()
.translationX(toX)
.setDuration(duration);

I think it's preferred one, because it doesn't call measure() and layout() on each update as the second one would.

And in general:
- translationX is meant to regulate the position of a child within its parent
- perform animation through changing margin parameter isn't a good idea (it's meant to be set once and to be changed rarely if ever)

Upvotes: 2

Related Questions