假设我有一个应用程序,它具有类似的按钮,它们的名称分别为button0,button1等,最高到button9。

如何在不复制代码的情况下执行以下操作?

button0 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button0);
button1 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button1);
...
button9 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button9);


我尝试使用反射,但是代码看起来不干净。

for (int i = 0; i <= 9; i++) {
    String btnName = "button" + i;
    /* do reflection stuff to link self.buttonX
       with a reference to com.sample.SampleApp.R.id.buttonX */
}

最佳答案

以下代码未经测试,请尝试一下:

Button[] buttons = new Button[]{button0, button1, button2, button3, button4, button5, button6, button7, button8, button9};
for (int i = 0; i < buttons.length, i++) {
   buttons[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}


使用ArrayList(再次未经测试-只是让您了解我的意思):

ArrayList<Button> buttons = new ArrayList<Button>();
for (int i = 0; i < 10, i++) {
   buttons.add(new Button(this));
   buttons.get(i) = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}

09-13 01:09