4

I've started using View Binding in my fragments and activities. The recommended pattern for Fragments is to null the binding field in onDestroyView(). I'm also using view binding in my custom views. Do I need to handle clearing that view binding field as well? I would assume so, but there is no onDestroyed() function for views. There is a View.onDetachedFromWindow() function but I'm not sure that would be an appropriate place to null the binding field.

Is this a valid concern and if so how can I accomplish it?

Somesh Kumar
  • 8,088
  • 4
  • 33
  • 49
szaske
  • 1,887
  • 22
  • 32

1 Answers1

6

It is a valid concern in fragments because the fragment instance can live much longer than its view. For example, when the fragment instance is on the back stack with its view already destroyed.

A custom view does not have such lifecycle issues. The view and its fields share the same lifecycle. You don't need a nullable binding field. The view and its binding ultimately get garbage collected when no longer referenced anywhere.

laalto
  • 150,114
  • 66
  • 286
  • 303