2012-11-24 50 views
5

對於我的android應用程序,我需要製作一個View ID的數組。你如何循環查看ID的?

該數組將保存81個值,因此將它們逐個添加非常冗長。 這是現在的樣子:

cells[0] = R.id.Square00; 
cells[1] = R.id.Square01; 
cells[2] = R.id.Square02; 
cells[3] = R.id.Square03; 
cells[4] = R.id.Square04; 
cells[5] = R.id.Square05; 
//All the way to 80. 

是否有這樣做的一個較短/更有效的方式?

+0

很多方面EED ..你可以用'SETID()'和'的getId()'動態代碼中的或有'getIndentifier()'從**資源的方法**班。 – user370305

回答

5

值得慶幸的是有,使用getIndentifier()

Resources r = getResources(); 
String name = getPackageName(); 
int[] cells = new int[81]; 
for(int i = 0; i < 81; i++) { 
    if(i < 10) 
     cells[i] = r.getIdentifier("Squares0" + i, "id", name); 
    else 
     cells[i] = r.getIdentifier("Squares" + i, "id", name); 
} 
+1

我會打電話getPackageName()一次循環 –

+0

當然,很容易。 – Sam

+0

謝謝,這就像一個魅力! –

1

薩姆的回答是好,但我覺得我應該分享山姆回答的替代

int [] ids = new int [] {R.id.btn1, R.id.btn2, ...}; 
Button [] arrayButton = new Button[ids.length]; 

for(int i=0 ; i < arrayButton.length ; i++) 
{ 
    arrayButton[i] = (Button) findViewById(ids[i]); 
} 

修改的形式

沒有n如果使用別的整數字符串格式化

Resources r = getResources(); 
String name = getPackageName(); 

int[] resIDs = new int[81]; 

for(int i = 0; i < 81; i++) 
{ 
     resIDs[i] = r.getIdentifier("Squares0" + String.format("%03d", i), "id", name); 
}