简体   繁体   English

Android R.java文件

[英]Android R.java file

Static id in R.java files are generated automatically but can i give then custom values to make my work easier. R.java文件中的静态ID是自动生成的,但我可以给出自定义值以使我的工作更轻松。 I have 8 Imagebuttons i need to set images on them by using this code for every button. 我有8个图像按钮我需要通过使用此代码为每个按钮设置图像。

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 而不是这样做我可以将R.java中的按钮的id更改为1,2,3 ...并将上面的代码放在这样的for循环中

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

You can't rely on the numbering, no. 你不能依赖编号,不。 You don't want to have to be manually changing R.java . 您不希望必须手动更改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);
}

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. 您可以将内部值的映射保存到R.java中的唯一ID。 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);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM