3

Static id in R.java files are generated automatically but can i give then custom values to make my work easier. I have 8 Imagebuttons i need to set images on them by using this code for every button.

ImageButton button4 = (ImageButton)findViewById(R.id.iButton4);
setImagesOnButtons(myContactList.get(3).getPhotoId(),button4);

instead of doing this can i change ids of button in R.java to 1,2,3... and put the above code in a for loop like this

 for(i=0;i<8;i++)
 {
ImageButton button4 = (ImageButton)findViewById(i);
setImagesOnButtons(myContactList.get(3).getPhotoId(),i);
} 
0

2 Answers 2

1

EDIT: Sean Owen's answer is nicer and more compact than this one.

You could keep a map from your internal values to the unique IDs in R.java. You only need to do this once, on startup:

static final Map<Integer,Integer> buttonMap = new HashMap<Integer,Integer>();

...
buttonMap.put(4, R.id.iButton4);
buttonMap.put(3, R.id.iButton3);
...

Then you can have your loop like this:

for(i=0;i<8;i++)
{
    ImageButton button = (ImageButton)findViewById(buttonMap.get(i));
    setImagesOnButtons(myContactList.get(3).getPhotoId(),i);
} 
Sign up to request clarification or add additional context in comments.

Comments

1

You can't rely on the numbering, no. You don't want to have to be manually changing R.java. Instead, do something like this:

int[] buttonIDs = {R.id.iButton1, R.id.iButton2, ...};
for (int i = 0; i < buttonIDs.length; i++) {
  int buttonID = buttonIDs[i];
  ImageButton button4 = (ImageButton) findViewById(buttonID);
  setImagesOnButtons(myContactList.get(3).getPhotoId(), i);
}

1 Comment

I have a doubt is there any specific reason u used buttonID in the for loop where you could have used buttonIDs[i] directly.

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.