Android view - onAttachedToWindow and onDetachedFromWindow - when are they called in the activity lifecycle?
Technically speaking onAttachedToWindow
is called after onResume
(and it happens only once perlifecycle).
ActivityThread.handleResumeActivity
call will add DecorView
to the current WindowManger
which will in turn call WindowManagerGlobal.addView()
which than traverse all the views and call onAttachedToWindow
on each view.
onDetachedFromWindow
is tied with onDestroy
I find it's possible that onAttachedToWindow
will be called when setContentView
is called.
When you use split screen on Android N, and the value of configChanges
of activity in AndroidManifest.xml
to be set:
"keyboardHidden|orientation|screenSize"
onAttachedToWindow
will be called in setContentView
, because the the variable "mAttachInfo" in the decorview of window is not null, when you call setContentView
to add rootView
to decorView
, dispatchAttachedToWindow
is called in addViewInner()
.
Finally after activity onResume()
, onAttachedToWindow()
is not be called again.
This is not really an answer but an advice ...
Many times, I've felt the urge to use this method (onDetachedFromWindow) to unregister observers and/or clear scopes...
DO NOT DO THIS!!
onDetachedFromWindow() does not equal Fragment's onDestroyView().
There is no inner method that gets called specifically when the view is destroyed (unfortunately).
onDetachFromWindow() will get called when changing the page in a ViewPager/ViewPager2, while the view is not really being destroyed. If you use onDetachFromWindow() to clear scopes, you'll either get a NullPointerException, or the view will simply stop responding to updates when scrolling back to the page in question.
The best and easiest thing you could do is use the onDestroyView() method to clear scopes.
The hardest/best way is to listen for the Fragment's LifeCycle (if you want a one time instantiated Adapter), and then dispatch an "destroyed" message through the Adapter to all views observing the Adapter and make them self-unregister themselves.... not even the DataSetObserver class is built to do this (when it should).