1

This seems very simple but I'm not understanding how to do this and haven't figured out how to phrase it for Google. I have a set of 12 ImageViews declared in XML, so I want to declare them all in a for loop, using something like

for(int i = 1; i < 13; i++) {
    ImageView moles[i] = FindViewById(R.id.mole + i);
}

But I'm not understanding how to declare the argument for FindViewById.

1
  • You can't, unless you use reflection, which you don't want to. Is there some Android API that lets you pass the ID as a string instead? Commented May 21, 2015 at 1:22

3 Answers 3

1

Generally you make a hard coded array of ids

int ids[] = {R.id.image1, R.id.imag2,...};
for(int i = 0; i < ids.size; i++) {
    ImageView moles[i] = FindViewById(ids[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

R.id.mole is dynamically generated by Android SDK. It is int, right, but you can't use as int because next one is not necessary previous+1.

If you use ids dynamically generated then assume they are random.

Comments

1

You can't do that. But the closest you can get is by doing this

private static final int[] imageArray = {R.id.mole1, R.id.mole2, R.id.mole3, R.id.mole4, R.id.mole5};
private ImageView[] moles= new ImageView[idArray.length];

Then your for loop would look something like this

for (int i=1; i<=imageArray.length; i++) {
    moles [i] = (ImageView)findViewById(idArray[i]); // Fetch the view id from array
    ....
}

1 Comment

The final isn't needed, unless you want to pass the index to a Listener you declare inside this loop. You can just use i

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.