Search code examples
androidviewcallbackandroid-activity

How to detect if view's parent activity is being destroyed


I want to do some cleanup in a view when the activity is being destroyed. Is there any way to get a callback in the View when the activity is being destroyed? I tried using onDetachedFromWindow, but I'm not sure whether it is correct thing to do.


Solution

  • With the understanding that onDestroy is not guaranteed to be called, you can just callback into your view in the activities onDestroy method.

    Edit in response to comment: You can get any view by giving it an id in the layout and calling findViewById. Here's an example:

    Layout.xml (only showing the bare minimum)

    <LinearLayout>
      <com.example.superwidget.DropDownTouchEnabledListView
        android:id="@+id/special_list_view" />
    </LinearLayout>
    

    MyActivity.java (again, bare minimal and assuming proper imports)

    @Override
    void onDestroy() {
        DownTouchEnabledListView v = (DownTouchEnabledListView)findViewById(R.id.special_list_view);
        v.doCallback(with, parameters);
    }