Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 684
bhups Avatar asked Jun 30 '10 08:06

bhups


2 Answers

If you want to get a callback without having to overload the View.onDetachedFromWindow() method, you may use the View.addOnAttachStateChangeListener() method, which takes a callback listener as a single parameter.

like image 184
Édouard Mercier Avatar answered Oct 04 '22 07:10

Édouard Mercier


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);
}
like image 45
Jere.Jones Avatar answered Oct 04 '22 07:10

Jere.Jones