[英]Android R.java file
R.java文件中的静态ID是自动生成的,但我可以给出自定义值以使我的工作更轻松。 我有8个图像按钮我需要通过使用此代码为每个按钮设置图像。
ImageButton button4 = (ImageButton)findViewById(R.id.iButton4);
setImagesOnButtons(myContactList.get(3).getPhotoId(),button4);
而不是这样做我可以将R.java中的按钮的id更改为1,2,3 ...并将上面的代码放在这样的for循环中
for(i=0;i<8;i++)
{
ImageButton button4 = (ImageButton)findViewById(i);
setImagesOnButtons(myContactList.get(3).getPhotoId(),i);
}
你不能依赖编号,不。 您不希望必须手动更改R.java
。 相反,做这样的事情:
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);
}
编辑:肖恩欧文的答案比这个更好,更紧凑。
您可以将内部值的映射保存到R.java中的唯一ID。 你只需要在启动时执行一次:
static final Map<Integer,Integer> buttonMap = new HashMap<Integer,Integer>();
...
buttonMap.put(4, R.id.iButton4);
buttonMap.put(3, R.id.iButton3);
...
然后你可以像这样循环:
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.