Search code examples
androidandroid-fragmentsandroid-lifecycleandroid-memorybutterknife

Should I delete the OnClickListener in onDestroyView?


I set listener for my button:

  View onCreateView(...) {
    ...
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //some work
        }
    });
    ...
}

If I use ButterKnife, it is recommended to call ButterKnife.unbind(this) in onDestroyView(){..}. Do I need to remove the listeners for avoid memory leak?

void onDestroyView() {
    ...
    btn.setOnClickListener(null)
}

Solution

  • It depends...

    Do you have different layouts for portrait and landscape, and you have it configured so that when you rotate only the view is destroyed?

    If so, YES to prevent references of an unused view on a used Activity/Fragment (that could prevent it from being GC)

    If when you rotate the view and Fragment/Activity is destroyed, then NO you don't need to do it, the GC will take care of it.

    This difference exists due to the fact that Android uses a Mark-Sweep algorithm on it's GC which will prevent the cases where 2 unused objects with references to each other (circular references) from being collected... but not the cases where a used object has a referenced to an unused one.


    Some useful Q&A about this: