簡體   English   中英

Android R.java文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM