I have a custom component which extends LinearLayout, I need to execute certain statements when Layout is destroyed or removed. (or about to be removed)
One way is to check for onPause() or onDestroy() of an activity and call methods of the custom component. But I want to remove that overhead from the activity.
So that custom component itself can handle when layout is detached. But I dint find the suitable method to override (to detect the event) when layout is removed. Is there a way to handle this, or we need to use onPause() and onResume() method of activity ?
It is dangerous to rely on the “destruction” of a layout to execute statements, as you’re not directly in control of when that happens. The accepted way and good practice is to use the activity’s lifecycle for that.
But if you really want to tie your component to that lifecycle, I suggest your component implements an interface (something like
Removable), and do something like that in your base activity classe (that all your activities extend):The interface:
Then each time you add one of your custom component from an activity, you add the component to the internal set of
Removableof the activity, and itsremovemethod will be automatically called each time the activity is paused.That would allow you to specify what to do when
onPauseis called within the component itself. But it wouldn’t ensure it’s automatically called, for that you’ll have to do it in the activity.Note: you can use
onStopinstead ofonPausedepending on when you want the removal to occur.