Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    // View is now attached
}

@Override
protected 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.

@Override
void onViewDetachedFromWindow(View v) {
 doCleanup();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top