0

I want to remove all imageviews on a relative layout in Android Studio, save them and replace them later.

RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
ArrayList al = rl.getTouchables();
rl.removeAllViews();
//do something
for(int i=0; i<al.size(); i++) 
{
 if(al.get(i).equals(new ImageView(this))) 
 rl.addView((ImageView) al.get(i));
} 

The programm is not working :(

1 Answers1

2

Find all the image views in the viewgroup using instanceof. Once you have them all, remove the images from the viewgroup. Then you can do whatever work you need to do on these images:

final ViewGroup vg = (ViewGroup) findViewById(R.id.relativeLayout);
final List<ImageView> images = new ArrayList<>();
for(int i = 0; i < vg.getChildCount(); i++) {
    final View v = vg.getChildAt(i);
    if (v instanceof ImageView) {
        images.add((ImageView) v);
    }
}
for (final ImageView v : images) {
    vg.removeView(v);
}

When java 8 rolls around I imagine we'd be able to do something like this:

final ViewGroup vg = (ViewGroup) findViewById(R.id.relativeLayout);
final List<ImageView> images = IntStream()
    .range(0, vg.getChildCount())
    .mapToObj(vg::getChildAt)
    .filter(ImageView.class::isInstance)
    .map(ImageView.class::cast)
    .collect(Collectors.toList());
images.stream().forEach(vg::removeView);
flakes
  • 21,558
  • 8
  • 41
  • 88