我在Activity中有这种类型的代码:
ImageButton button1 = (ImageButton)findViewById(R.id.butid1);
ImageButton button2 = (ImageButton)findViewById(R.id.butid2);
ImageButton button3 = (ImageButton)findViewById(R.id.butid3);
现在我想在for循环中声明这些变量。此外,将使用这N个按钮执行操作。例如:
for (int NUMBER = 1; NUMBER <= N; NUMBER++) {
ImageButton button"NUMBER" = (ImageButton)findViewById(R.id.butid"NUMBER");
button"NUMBER".setEnabled(false);
}
N会根据不同的情况而改变。我能做些什么来解决这个问题? (P.S.无法在“具有相似头衔的问题”中找到结果)
答案 0 :(得分:2)
在循环之前,将所有按钮放入Button数组中。因此,您可以根据需要简单地遍历数组。
ImageButton[] buttons = new ImageButton[<put here the total number of Buttons>];
buttons[0] = (ImageButton)findViewById(R.id.butid1);
buttons[1] = (ImageButton)findViewById(R.id.butid2);
...
buttons[N-1] = (ImageButton)findViewById(R.id.butidN);
for (int i = 0; i < N; i++) {
buttons[i].setEnabled(false);
}
答案 1 :(得分:0)
使用ImageButton[] button = new ImageButton[NUMBER]
然后你的for循环应该是:
for (int i = 0; i < NUMBER; i++) {
ImageButton button[i] = (ImageButton)findViewById(R.id [***]);
button[i].setEnabled(false);
}
[ * ]我不知道Android,但我想有一种方法可以将所有按钮作为某种列表或数组,这样您就不需要访问它们了每个由Id。