java - 在 for 循环中声明变量,将整数转换为字符串 (Android/Java)

标签 java android

<分区>

Possible Duplicate:
Android findViewbyId with a variant string

我在 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. 在“同题题”中找不到结果)

最佳答案

在循环之前,将所有 Button 放入一个 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);
}

关于java - 在 for 循环中声明变量,将整数转换为字符串 (Android/Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8687798/

相关文章:

java - Gradle Android 错误 : MethodHandle. 调用和 MethodHandle.invokeExact

java - 自动提交并不总是发生

java - 泛型通配符方法的编译错误

java - 如何在Android中添加2个org.opencv.core.Point对象?

android - 如何运行 chrome 工具而不是浏览器

android - 哪个 API 版本适用于 Android 2.3.6?

java - 为什么在文件服务器程序套接字中写入 "Socket s =null"?

java - 读取文本文件和处理每一行的最干净的方法

Java 包/库函数

android - 修改listview tem OnActivityResult