1

This may be a simple problem that has been asked before, but I do not even know what I would search to find the solution, so I am going to ask it here.

I have 4 ImageView's that all have the same name except they have an increasing number at the end of their names. So for example:

    final ImageView circle1 = findViewById(R.id.p1circle1);
    final ImageView circle2 = findViewById(R.id.p1circle2);
    final ImageView circle3 = findViewById(R.id.p2circle1);
    final ImageView circle4 = findViewById(R.id.p2circle2);

And I want to cycle through these based off a variable in a for loop. This is the for loop I have created

for(int i = 0; i < wins1; i++) {
    circle +i .setBackground(getResources().getDrawable(R.drawable.circle2);
}

I am trying to cycle through the different ImageView names by adding the increasing i variable to the end of the name, but this is obviously the incorrect way to go about it.

How can I cycle through these variable names based on the variable i?

brent_mb
  • 337
  • 1
  • 2
  • 14

1 Answers1

2

Java is pass by value so you are correct in saying you cannot just add a number to a variable name and expect it to reference a different variable.

The solution to this problem is to add your ImageViews into an iterable data structure, most commonly an ArrayList. From there you can reference the indexes of the array list using the get method, rather than directly calling the variables by their names. (you might not even need to save the object into a variable if you don't need to reference it in a different way)

Something like:

ArrayList<ImageView> circleList = new ArrayList<>();

//Add 4 new ImageViews to the list
for (int i = 0; i < 4; i++) {
    circleList.add(new ImageView());
}

for(int j = 0; j < wins1; j++) {
    circleList.get(j).setBackground(getResources().getDrawable(R.drawable.circle2);
}
NotZack
  • 518
  • 2
  • 9
  • 22