繁体   English   中英

Android Studio:Java:使用 ID 用按钮填充二维数组

[英]Android Studio: Java: Populating 2D Array with buttons using IDs

我正在尝试用按钮填充二维数组,以创建 tic tac toe 类型的游戏,大小为 5x5。

到目前为止,我想出了这个:(不工作)

private Button[][] gameArray = new Button[5][5];
for (int x = 0; x<5; x++) {
      for (int y = 0; x < 5; y++) {
          String gameButtonId = "buttons" + x + y;
          int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
          gameArray[x][y] = findViewById(gameID);
          gameArray[x][y].setOnClickListener(this);

我创建了具有特定 id 的按钮,如下所示:第一行有按钮 id:buttons00、buttons01、buttons02、buttons03、buttons04,第二行是:buttons10、buttons11、buttons12、buttons 13、buttons14 等等......直到有是网格上的 25 个按钮。

我将如何使用这些按钮及其 ID 有效地填充二维数组?

你的内循环是错误的! 你一直运行到x < 5 ,但它应该是y < 5

您的代码应如下所示:

private Button[][] gameArray = new Button[5][5];
for (int x = 0; x < 5; x++) {
      for (int y = 0; y < 5; y++) {
          String gameButtonId = "buttons" + x + y;
          int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
          gameArray[x][y] = findViewById(gameID);
          gameArray[x][y].setOnClickListener(this);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM