Autoincrement on Android components

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 does auto increment in the declared components?

For example, something that is increasing img : img1 , img2 , img3 ... imgN .

    
asked by anonymous 09.12.2017 / 21:46

1 answer

1

Try something like this:

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

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

It may make sense to put something like this shortly afterwards (note that it is now white, not black):

for (int i = bolaPreta; i < views.length; i++) {
    views[i].setImageResource(R.drawable.icon_circbranco);
}
    
10.12.2017 / 01:31