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):
protected Set<Removable> myRemovableItems = new HashSet<Removable>();
@Override
public void onPause() {
super.onPause();
for (Removable removable : myRemovableItems) {
removable.remove();
}
}
The interface:
public interface Removable {
void remove();
}
Then each time you add one of your custom component from an activity, you add the component to the internal set of Removable
of the activity, and its remove
method will be automatically called each time the activity is paused.
That would allow you to specify what to do when onPause
is 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 onStop
instead of onPause
depending on when you want the removal to occur.