简体   繁体   中英

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

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() ?

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM