假设我有一个应用程序,它有类似的按钮,名称为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"));
}