假设我有一个名为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 */
}
答案 0 :(得分:1)
以下代码未经测试,但请尝试一下:
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"));
}