0

I'm trying to animate a view movement in RelativeLayout with respect to others views' position.

So my layout looks like this:

<RelativeLayout>
     <View alignParentLeft>
     <View centerHorizontal>
     <View alignParentRight>
     <AnimatedView>
</RelativeLayout>

I use ObjectAnimator to animate this view:

ObjectAnimator.ofFloat(animatedView, "x", animatedView.getX(), childView.getX());

But all child views except the one I'm trying to animate, returns 0 for getX() or getLeft().

I'd appreciate any help.

andrei_zaitcev
  • 1,358
  • 16
  • 23
  • 1
    http://stackoverflow.com/questions/3619693/getting-views-coordinates-relative-to-the-root-layout – koutuk Oct 26 '15 at 12:28

1 Answers1

0

It's probably due to the fact that when you're trying to start your Animation your Views don't have dimensions yet (have not been drawn yet). Are you trying to start your animation in something like Activity's onCreate or Fragment's onCreateView?

To make sure your Views are ready to be animated you can use for example this:

yourRelativeLayout.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
       int width = yourRelativeLayout.getWidth();
       int height = yourRelativeLayout.getHeight();
        if (width > 0 && height > 0) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
              yourRelativeLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
              yourRelativeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }

            //START YOUR ANIMATION HERE
        }
    }
});
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132