Method to override when layout is destroyed in Android Method to override when layout is destroyed in Android android android

Method to override when layout is destroyed in Android


I had success overriding the onAttachedToWindow() and onDetachedFromWindow() methods:

@Overrideprotected void onAttachedToWindow() {    super.onAttachedToWindow();    // View is now attached}@Overrideprotected void onDetachedFromWindow() {    super.onDetachedFromWindow();    // View is now detached, and about to be destroyed}


You can have your custom view listen to its own eventss. I suggest using View.OnAttachStateChangeListener and listening to onDetach event.

@Overridevoid onViewDetachedFromWindow(View v) { doCleanup();}


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>();@Overridepublic 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.