Android view - onAttachedToWindow and onDetachedFromWindow - when are they called in the activity lifecycle?

j2emanue picture j2emanue · Feb 9, 2017 · Viewed 13.9k times · Source

I believe that onAttachedToWindow() is called when the onCreate()'s setContentView(R.layout.myLayout.xml) is called. So can I assume then that in the activity lifecycle that onDetachedFromWindow() is called when the activity is destroyed? My question is how do I tie these two call back hooks to the activities lifecycle?

Can I say that onAttachedToWindow() is tied to onCreate() and onDetachedFromWindow() is tied to onDestroy()?

Answer

WenChao picture WenChao · Feb 9, 2017

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