【问题标题】:Android Studio: Java: Populating 2D Array with buttons using IDsAndroid Studio:Java:使用 ID 填充带有按钮的 2D 数组
【发布时间】:2020-10-08 20:57:27
【问题描述】:

我正在尝试使用按钮填充 2d 数组,以创建大小为 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个button。

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

【问题讨论】:

    标签: java android arrays button


    【解决方案1】:

    你的内循环是错误的!你一直跑到x &lt; 5,但它应该是y &lt; 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);
    

    【讨论】:

      猜你喜欢
      • 2013-05-26
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2017-03-26
      • 2021-09-27
      • 2018-03-08
      相关资源
      最近更新 更多