Auto-increment in Android components

Asked

Viewed 31 times

1

Good people, I have the following code:

            if (bolaPreta == 1) {
                img1.setImageResource(R.drawable.icon_circpreto);
            }
            if (bolaPreta == 2) {
                img1.setImageResource(R.drawable.icon_circpreto);
                img2.setImageResource(R.drawable.icon_circpreto);
            }
            if (bolaPreta == 3) {
                img1.setImageResource(R.drawable.icon_circpreto);
                img2.setImageResource(R.drawable.icon_circpreto);
                img3.setImageResource(R.drawable.icon_circpreto);
            }

Is there any possibility of changing this type of programming to something that makes auto increment in the declared components?

For example: Something that increased the img: img1, img2, img3 ... imgN.

  • When bolaPreta == 1 what is assigned to img2 and img3? What is the maximum value of images(imgN)?

  • The maximum image value is 10. When the ballPreta == 1 is assigned nothing, img2 and img3 do not appear in the interface.

1 answer

1

Try something like that:

ImageView[] views = new ImageView[] { img1, img2, img3 /*, ..., imgN*/ };

for (int i = 0; i < bolaPreta; i++) {
    views[i].setImageResource(R.drawable.icon_circpreto);
}

Maybe it makes sense to put something like this right after (note that it is now white, not black):

for (int i = bolaPreta; i < views.length; i++) {
    views[i].setImageResource(R.drawable.icon_circbranco);
}
  • I haven’t had a chance to test yet, but when I do I’ll give my feedback!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.