您可以創建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
具體方法(如getResources
,getIdentifier
)才達到相同的結果,並且不能在通常的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事件。
+1但請注意,這很慢。 –
@AleksG你有其他選擇嗎? – Richard
@Richard沒有其他選擇 - 這是唯一的方法,而且速度很慢。如果您需要這樣做,您可能需要重新考慮您的邏輯。例如,在代碼中創建按鈕而不是XML,並在創建時將它們存儲在數組中。然後你只需要遍歷你的數組。 –