1

Let's say I have 150 pictures. I need to change their visibility or even resource with loop to not do it for every one photo by typing.

I tried to loop it like this:

final ImageView randompic1 = (ImageView) findViewById(R.id.pic1);
final ImageView randompic2 = (ImageView) findViewById(R.id.pic2);
final ImageView randompic3 = (ImageView) findViewById(R.id.pic3);
final ImageView randompic4 = (ImageView) findViewById(R.id.pic4);
//(etc.)

    for (int j = 0; j <=150; j++){
            randompic(j).setVisibility(View.INVISIBLE);
                             };

So I would like to change it in loop to be like: randompic(j).setVisibility(View.INVISIBLE) for randompic1, randompic2, randompic3 etc. in each loop. Java do not accept this kind of typing like JavaScript. I do not know how to find good way to write that kind of loop.

1
  • setting 150 different things to true/false already seems like an inefficient Commented Jul 7, 2021 at 13:29

1 Answer 1

1

Add your ImageViews to a List and change the visibility of every item in this list like this:

List<ImageView> randompics = new ArrayList<>();
randompics.add((ImageView) findViewById(R.id.pic1));
randompics.add((ImageView) findViewById(R.id.pic2));
randompics.add((ImageView) findViewById(R.id.pic3));
randompics.add((ImageView) findViewById(R.id.pic4));
//(etc.)

for (int j = 0; j <= randompics.size(); j++) {
    randompics.get(j).setVisibility(View.INVISIBLE);
};

Instead of the classic for-loop you can also use foreach like this:

randompics.foreach(pic -> pic.setVisibility(View.INVISIBLE));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.