2014-01-26 36 views
2

我有16個按鈕,其名稱分別是「button1」,「button2」等。有沒有一種方法可以使用for循環遍歷它們,以某種方式在每次迭代時附加數字值?事情是這樣的:使用for循環編輯幾個按鈕的文本

for(int i = 1; i<17; i++){ 
     Button b = (Button)findViewById(R.id.buttoni); 

我知道我可以簡單地在我的onCreate()方法初始化每個按鈕,但我只是好奇,如果我能在類似於我的示例代碼的方式做到這一點。

謝謝。

回答

3

您可以使用getIdentifier

for(int i = 1; i<17; i++){   
    int buttonId = getResources().getIdentifier("button"+i, "id", getPackageName()); 
    Button b = (Button)findViewById(buttonId); 
    //Your stuff with the button 
} 
+1

+1但請注意,這很慢。 –

+0

@AleksG你有其他選擇嗎? – Richard

+2

@Richard沒有其他選擇 - 這是唯一的方法,而且速度很慢。如果您需要這樣做,您可能需要重新考慮您的邏輯。例如,在代碼中創建按鈕而不是XML,並在創建時將它們存儲在數組中。然後你只需要遍歷你的數組。 –

1

您可以創建Button的數組並用getIdentifier方法,可以讓你得到它的名字的標識符。

final int number = 17; 
final Button[] buttons = new Button[number]; 
final Resources resources = getResources(); 

for (int i = 0; i < number; i++) { 
    final String name = "btn" + (i + 1); 
    final int id = resources.getIdentifier(name, "id", getPackageName()); 

    buttons[i] = (Button) findViewById(id); 
} 

如果有人感興趣如何使用Java僅

上面的解決方案使用Android具體方法(如getResourcesgetIdentifier)才達到相同的結果,並且不能在通常的Java使用,但我們可以用一個reflection,寫的作品就像一個getIdentifier的方法:

public static int getIdByName(final String name) { 
    try { 
     final Field field = R.id.class.getDeclaredField(name); 

     field.setAccessible(true); 
     return field.getInt(null); 
    } catch (Exception ignore) { 
     return -1; 
    } 
} 

然後:

final Button[] buttons = new Button[17]; 

for (int i = 0; i < buttons.length; i++) { 
    buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1))); 
} 

NOTE:

優化這種代碼,而不是你應該重新考慮佈局。如果屏幕上有17個按鈕,則ListView可能是更好的解決方案。您可以通過索引訪問項目,並像使用按鈕一樣處理onClick事件。