您可以创建一个由组成的数组,
Button并使用
getIdentifiermethod,该方法允许您通过名称获取标识符。
final int number = 30;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和编写一种类似于a的方法
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[30];for (int i = 0; i < buttons.length; i++) { buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));}


