android销毁时有视图回调吗?
android is there any view callback when it's destroyed?
我有一个自定义视图组件。我在片段或 activity 中使用了它。我想知道从fragment/activity?
销毁时是否有回调
View 没有回调(finalize()
除外,但我认为这不是您所要求的)。视图从屏幕上移开时有 onDetachedFromWindow()
,但这与它被销毁无关——它可以再次附加,这将调用 onAttachedToWindow()
.
片段有onDestroyView()
,可能对你更有用。 Activity 没有等效的方法,但您可以使用 onDestroy()
,只要您知道如果系统决定意外终止您的应用程序,它可能永远不会被调用。
感谢 Karakuri 的回答,可选的解决方案(使用简单的回调)
Note
view OnLayoutChangeListener
not called before view detached from window
view.listener = object :OnViewAttachedChangeListener{
override fun onAttachedFromWindow(view: View, isAttached: Boolean) {
}
}
添加用于跟踪附件状态的简单回调。
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)
}
我有一个自定义视图组件。我在片段或 activity 中使用了它。我想知道从fragment/activity?
销毁时是否有回调View 没有回调(finalize()
除外,但我认为这不是您所要求的)。视图从屏幕上移开时有 onDetachedFromWindow()
,但这与它被销毁无关——它可以再次附加,这将调用 onAttachedToWindow()
.
片段有onDestroyView()
,可能对你更有用。 Activity 没有等效的方法,但您可以使用 onDestroy()
,只要您知道如果系统决定意外终止您的应用程序,它可能永远不会被调用。
感谢 Karakuri 的回答,可选的解决方案(使用简单的回调)
Note
view OnLayoutChangeListener
not called before view detached from window
view.listener = object :OnViewAttachedChangeListener{
override fun onAttachedFromWindow(view: View, isAttached: Boolean) {
}
}
添加用于跟踪附件状态的简单回调。
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)
}