是否有必要在分离时将Fragment接口侦听器设置为null? [英] is it necessary to set Fragment interface listeners to null on detach?

查看:125
本文介绍了是否有必要在分离时将Fragment接口侦听器设置为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在涉及回调的Fragment示例中,通常它们在onAttach方法中分配侦听器,然后在onDetach方法中将侦听器设置为null。

In Fragment examples involving callbacks, usually they assign the listener in the onAttach method and then set the listener to null in the onDetach method.

这是否是必要的最后一部分?当片段被分离/销毁时,侦听器是否自动设置为null?或者在某些情况下你可能会分离片段并将其重新附加到其他地方,并且你不希望回调指向任何特定的东西,直到它被重新附加到某些东西上?

Is this last part necessary? Doesn't the listener automatically get set to null when the fragment is detached / destroyed? Or are there situations where you might detach the fragment and re-attach it somewhere else, and you wouldn't want the callback pointing to anything in particular until it gets reattached to something?

推荐答案

我从未明确设置对 null 的侦听器引用,因为在大多数情况下它不会产生任何影响。

I have never explicitly set listener references to null, since in most cases it won't make a difference.

以下是对其他问题的一些澄清:

Here are some clarifications on your other questions:


  • 听众不自动片段分离/销毁时设置为null?不是真的。 onDetach() onDestroy()反映组件生命周期,但不反映对象生命周期。那里什么都不会自动发生。当你的片段实例被垃圾收集时,对它的引用将被破坏。如果这是对你的监听器的唯一引用,那么它也有资格进行垃圾收集。

  • 或者在某些情况下你可能会分离片段并将其重新附加到其他地方,而你不希望回调指向任何特定的东西,直到它重新附加到某些东西?我会说这是不太可能的。在正常用例中,您必须在 onAttach()中分配侦听器,因此您确信可以正确委派事件。在 onDetach()之后,在重新附加片段之前,您将不会收到任何需要委派的事件。并且,如果你重新附加它,那么你将拥有正确的监听器实例,因为你已经在 onAttach()中处理了这个。

  • Doesn't the listener automatically get set to null when the fragment is detached / destroyed? Not really. onDetach() and onDestroy() reflect the component lifecycle, but not the object lifecycle. Nothing automatic will happen there. When your fragment instance is garbage collected, the reference to the listener will be destroyed with it. If this is the only reference to your listener, it will be also eligible for garbage collection.
  • Or are there situations where you might detach the fragment and re-attach it somewhere else, and you wouldn't want the callback pointing to anything in particular until it gets reattached to something? I would say that this is highly unlikely. In a normal use case, you would have to assign the listener in onAttach(), so you are sure that you can delegate events properly. After onDetach(), you won't receive any events that will require delegation, until you re - attach the fragment. And, if you re - attach it, then you will have the correct listener instance, since you have already taken care of that in onAttach().

这篇关于是否有必要在分离时将Fragment接口侦听器设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆