views:

27

answers:

1

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.

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
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
"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
@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
@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
@Jere.Jones: you're welcome!
CommonsWare
@bhups: In that case, stick with `onDetachedFromWindow()`, unless it causes problems.
CommonsWare