java - 在for循环Java中更改变量名称

标签 java variables for-loop

<分区>

我在板上有一个 6 个骰子的网格,我想在 Android Studio 中将其作为 imageButtons 进行访问。每个图像按钮都有一个 ID(按钮 1 是“ImageButton1”,而按钮 2 是“ImageButton2”等)。我想在一个 for 循环中访问这些按钮,而不是编写六个半相同的语句,如下所示:

for (int i=0; i<6; i++) {
        ImageButton c+i = (ImageButton)findViewById(R.id.imageButton+i);
}

imageButtton1 将存储在变量 c1 中,依此类推。显然,这个 for 循环并不像写的那样工作。有什么办法可以实现吗?

最佳答案

不幸的是,您不能通过名称动态访问 Java 变量。

但是您能否一次性将它们添加到列表中。

List<ImageButton> allButtons = new ArrayList<>() {{
    add((ImageButton) findViewById(R.id.imageButton1));
    add((ImageButton) findViewById(R.id.imageButton2));
    add((ImageButton) findViewById(R.id.imageButton3));
    // etc.
}};

这样您就可以通过轻松迭代来简化其余代码。

for (ImageButton button : allButtons) {
    ...
}

或者,您可以创建一个方法来按索引返回图像按钮:

private ImageButton imageButton(int index) {
    switch (index) {
        case 1: return (ImageButton) findViewById(R.id.imageButton1);
        case 2: return (ImageButton) findViewById(R.id.imageButton2);
        case 3: return (ImageButton) findViewById(R.id.imageButton3);
        //etc.
    }
}

虽然这是重复的,但它简单易读,而且都在一个地方——即应该易于维护。

关于java - 在for循环Java中更改变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42793528/

相关文章:

java - 为什么在 JVM 中运行的每个线程中一次只能激活一个方法?

java - JSP 对内部类使用 forEach

java - 类中主方法中 'if' 循环之外的变量范围 - 不可用问题

c# - 在 C# 中查找匹配的单词

java - 如何从后台通过连接状态更改 Firebase 数据库?

java undefined reference `main'收集2 : ld returned 1 exit status

asp.net - 如何在 Visual Studio 2008 调试器中查看 session 变量?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c - C 中简单 for 循环中的预期标识符或 '('

javascript - 使用 getElementById 和 addEventListener 停止网络音频鼓循环