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.
views:
27answers:
1
A:
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);
}
Jere.Jones
2010-06-30 08:52:09
Can you elaborate a little bit on this. My custom view class is part of a separate package and this view is defined in the layout xml. So invoking something on view from activity class is not feasible.
bhups
2010-06-30 08:57:07
"So invoking something on view from activity class is not feasible." Sure it is. Call `findViewById()`, get the widget, cast it to the appropriate class, and call a method on it. That being said, `onDetachedFromWindow()` seems like a reasonable choice to me.
CommonsWare
2010-06-30 09:20:49
@CommonsWare you comment faster than I can edit. :) BTW, thanks for all the work you do. Your books/code/answers have been invaluable to me.
Jere.Jones
2010-06-30 09:26:10
@CommonWare: I am writing a library which has custom views, on the contrary to writing an android app. So I have no control over the Activity class code.
bhups
2010-06-30 09:35:58
@Jere.Jones: you're welcome!
CommonsWare
2010-06-30 10:13:21
@bhups: In that case, stick with `onDetachedFromWindow()`, unless it causes problems.
CommonsWare
2010-06-30 10:13:45