Animating Margin by ValueAnimator vs ViewPropertyAnimator translationX

一世执手 提交于 2019-12-11 11:49:29

问题


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.


回答1:


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)




回答2:


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



来源:https://stackoverflow.com/questions/33085311/animating-margin-by-valueanimator-vs-viewpropertyanimator-translationx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!