is it necessary to set Fragment interface listeners to null on detach?

后端 未结 4 1200
感动是毒
感动是毒 2021-01-11 18:50

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.

Is this l

4条回答
  •  一生所求
    2021-01-11 19:09

    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:

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

提交回复
热议问题