android is there any view callback when it's destroyed?

不羁岁月 提交于 2020-06-27 06:40:14

问题


I have a custom view component. I used it in either fragment or activity. I would like to know if there's a callback when it's destroyed from fragment/activity?


回答1:


View does not have a callback (except finalize(), but I don't think that's what you're asking for). View has onDetachedFromWindow() when it is removed from the screen, but this is not related to it being destroyed -- it could be attached again, which will call onAttachedToWindow().

Fragment has onDestroyView(), which may be more useful to you. Activity doesn't have an equivalent method, but you could use onDestroy() as long as you know it may never be called if the system decides to terminate your app unexpectedly.




回答2:


Thanks for Karakuri answer, for optional solution (use simple callback)

Note

view OnLayoutChangeListener not called before view detached from window

   view.listener = object :OnViewAttachedChangeListener{
                    override fun onAttachedFromWindow(view: View, isAttached: Boolean) {
    
                    }
                }

Add simple callback for tracking attachment state.

   internal class AttachedView(context: Context): View(context){

        internal var listener: OnViewAttachedChangeListener?= null
            get() = field

        override fun onDetachedFromWindow() {
            super.onDetachedFromWindow()
            notifyOnAttachedToWindow(false)
        }

        override fun onAttachedToWindow() {
            super.onAttachedToWindow()
            notifyOnAttachedToWindow(true)
        }

        private fun notifyOnAttachedToWindow(isAttached: Boolean){
            listener?.onAttachedFromWindow(this, isAttached)
        }
    }

    internal interface OnViewAttachedChangeListener{
        fun onAttachedFromWindow(view: View, isAttached: Boolean)
    }


来源:https://stackoverflow.com/questions/31575486/android-is-there-any-view-callback-when-its-destroyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!