1

First of all, Let me aplogize, but I didnt know where else to ask.

I want to understand the following code that can be found here.

I understand all of it apart from the getViewTreeObserver bit:

movingView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        yAnimation = createSpringAnimation(movingView,SpringAnimation.Y, movingView.getY(), STIFFNESS, DAMPING_RATIO);
        xAnimation = createSpringAnimation(movingView,SpringAnimation.X, movingView.getX(), STIFFNESS, DAMPING_RATIO);
        movingView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

Why do we need this bit? The last line, removes the OnGlobalLayoutListener from the movingView, so I dont understand why we set it and then remove it. If I take the yAnimation and xAmination lines out of this listener, and just run them on their own, the code still works fine however it doesn't return to its original X and Y. But I dont understand why the above code allows the createSpringAnimationfunction to receive the correct X and Y.

Please, can someone help me understand?

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
Chud37
  • 4,907
  • 13
  • 64
  • 116
  • https://developer.android.com/reference/android/view/ViewTreeObserver – Vidhi Dave Sep 25 '18 at 09:06
  • Theres also another explanation here https://stackoverflow.com/questions/43633485/why-we-use-viewtreeobserveraddongloballayoutlistener – Jevon Jul 01 '20 at 00:39

1 Answers1

2

Android needs time to lay out the Views in your layout. If you try to read any parameter of the View straight away you normally get 0 or any default value that the framework uses before managing to calculate the correct value. Since this operation is asynchronous you need to register a listener to be notified when the layout is ready. Then, of course, you can read the values and remove the listener because it is not necessary anymore. Be careful though because sometimes the listener is called multiple times so before using the values and before unregistering the listener check that you actually managed to read meaningful values.

kingston
  • 11,053
  • 14
  • 62
  • 116