Android - Remove views in a layout recursively
Is there a way to remove the views from a layout recursively? The function removeAllViewsInLayout() does not seem to do the task (it removes all views from a layout, but not the layout's children views). In my program, I add some FrameLayouts dynamically over a RelativeLayout, and over th开发者_JS百科ese FrameLayouts I add some ImageViews and TextViews. So I want to know if I'll have to go make my own recursive removing-view-code or if there is some available.
I think you can consider the layout as a tree. Thus, you only need a reference to the root node. If you remove it, it will be collected along with its children, since nothing else references them.
If for some reason you still see some Views after this operation, it means they belonged to a different node. You can always use the Hierarchy Viewer to "see" your UI better: http://developer.android.com/guide/developing/debugging/debugging-ui.html
It isn't a recursive example, but I believe that it can solve your problem:
public void ClearRelLayout(RelativeLayout RL){
for(int x=0;x<RL.getChildCount();x++){
if(RL.getChildAt(x) instanceof FrameLayout){
FrameLayout FL = (FrameLayout) RL.getChildAt(x);
FL.removeAllViewsInLayout();
}
}
RL.removeAllViewsInLayout();
}
Rather than using recursion, just loop through each child and clear it if it is a FrameLayout
First, normally you should call removeAllViews()
instead of removeAllViewsInLayout()
read the JavaDoc for the difference.
Also neither of these functions are recursive, they only remove the views from the object it is called on. Sub-structures will not change. This might cause problems and even memory leaks, if they have references to other objects that are kept.
For example if you have the following structure:
<LinearLayout id='top'>
<LinearLayout id='sub'>
<Button id='b'/>
</LinearLayout>
</LinearLayout>
and call removeAllViews()
on top
the layout sub
will still refer b
(and b
will refer sub
as parent). This means that you cannot reuse b
somewhere else without first removing it parent (sub
). If you do you will get an Exception.
精彩评论