Search code examples
javaandroidviewandroid-relativelayout

Simple way to remove all custom ImageViews in Relative Layout


I have a main relative layout that has CustomImageView's in it. This class extends ImageView with nothing special, just a different name so they can be identified easier. What i'm trying to do is remove all instances of this CustomImageView from the main layout.

My question is how do you do this when they are nested all over the place? For instance, they can directly be children of the main layout, but they can also be children that are in RadioGroups and LinearLayouts.

Is there a simple method that I can call on the relative layout and it will remove all instances of CustomImageView that are inside of it? Similar to RemoveAllViews(), except remove all of a specific type.


Solution

  • You can do this with a method that iterates over the children of a ViewGroup, and removes a child if it's an instance of your custom View, or recursively calls itself if the child is another nested ViewGroup. For example:

    private void removeCustomImageViews(final ViewGroup vg) {
        final int childCount = vg.getChildCount();
    
        for(int i = 0; i < childCount; i++) {
            final View child = vg.getChildAt(i);
    
            if(child instanceof CustomImageView) {
                vg.removeView(child);
            }
            else if(child instanceof ViewGroup) {
                removeCustomImageViews((ViewGroup) child);
            }
        }
    }
    

    Just call this method with your main RelativeLayout as the argument.