Andra Soto Andra Soto - 1 year ago 94
Android Question

Android - Should I use ViewGroup when close/null all views?

I have one question about when closing my activity and letting it be destroyed.

I think, in my java class that is going to reference my views (for example, my java class references my buttons and textviews on the screen), is it ok for me to put all the view references into a ViewGroup for the purpose of closing them out 100% later?

Sorry for my poor English. Let me further explain:

I create (in java class) variables for my button, textview, and other screen items, and put them into a group so when I want to delete them (null them) later, I can tell Android to delete all the child of the group? Also, maybe I can use group of all my buttons to do loop later too.

Is this bad practice? Is this ok to do this or is this not the intention of the ViewGroup? I read document on ViewGroup, but it does not say about if this is also a use for View Group.

Thank you for all answers. I am learning every day.

Answer Source

When designing a view, you use layout xml typically. That's loaded into Activity's onCreate() as a view. So in layout xml, you're required to use any layout managers, like LinearLayout, RelativeLayout, FrameLayout etc. They're all child of ViewGroup. So by default, every view is contained in a ViewGroup already.

Regarding your question about destroying, if there's no special case that is retaining the view and its child views, Activity's default implementation will take care of destroying the view and letting it get garbage collected.

Have a look at document reference of onDestroy() funtion, also the method onDetachedFromWindow() is worth looking at.

If you've a special case, that's retaining the view, overriding the onDetachedFromWindow() is a good place to release those views.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download