2

I am working on an app which listens for View events like scrolling, layout drawn using ViewTreeObserver. ViewTreeObserver has a method to check if it's alive before doing anything eg. adding listeners.

I have to reproduce the issue of dead / not alive ViewTreeObserver to see If my code works well in production. I don't see anything in android documentation to reproduce it.

I appreciate any help / pointers.

Thanks

Pradeep
  • 6,303
  • 9
  • 36
  • 60

2 Answers2

1

In fact, if you check the source code of class ViewTreeObserver, there is a "kill" function to set mAlive to false, also only here, but it is never invoked.

/**
 * Marks this ViewTreeObserver as not alive. After invoking this method, invoking
 * any other method but {@link #isAlive()} and {@link #kill()} will throw an Exception.
 *
 * @hide
 */
private void kill() {
    mAlive = false;
}

In my opinion, this observer will become unavailable (but is not un-alive, you couldn't use isAlive() to determine current observer's state) after:

  1. You removed listener(s), such as view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

  2. The current activity containing the view is destroyed

Vincent
  • 199
  • 1
  • 2
  • 10
1

If getViewTreeObserver is called before the view is attached, a variable mFloatingTreeObserver is returned. When the view is attached the first observer's listeners will be merged with the parent's listeners and the first getViewTreeObserver that you obtained will no longer be alive, as kill() is called in that merge method

andrei
  • 2,934
  • 2
  • 23
  • 36