Search code examples
javaandroidxmlfindviewbyid

I want to include several ImageViews from xml file in Android Studio


I want to include several ImageViews from xml file in Android Studio into my java class to modify them later during runtime. I have a way how it works but I am sure it is not the best.

List<ImageView> pictures= new ArrayList<>();
    pictures.add((ImageView) findViewById(R.id.picture0));
    pictures.add((ImageView) findViewById(R.id.picture1));
    ...

There must be a more efficient way, right? I named the ID of the ImageViews in the xml like pictureX where X is the number of the picture. Thus - I thought - I could somehow iterate over these IDs like

    for (int i=0; i<24; i++){
        String s = "R.id.picture" + i;
        pictures.add((ImageView) findViewById(s));
    }

but it does not work of course because the inconvertible types. The parameter of findViewById must be an int...

Is there a way to get those ImageViews in a loop or do I really have to get every ImageViewon its own?

I am grateful for every answer. :)


Solution

  • You may use ViewGroup.getChildAt()

    for(int i = 0; i < container.getChildCount(); i++){
        pictures.add((ImageView)container.getChildAt(i));
    }
    

    You may also add cast checker for complex child views so that it doesn't throw ClassCastException

    for(int i = 0; i < container.getChildCount(); i++){
       if(container.getChildAt(i) instanceof ImageView)
          pictures.add((ImageView)container.getChildAt(i));
    }