java - 如果每次制作新游戏时都会在网格中生成这些按钮,我是否必须在 xml 中定义屏幕上的每个按钮?

标签 java android xml

我正在开发一个小型个人项目,将我制作的同一游戏的一个版本移植到 Android 上。我用java编写了大部分游戏(仍在完成),但我正在阅读有关android开发的内容(阅读文档并在youtube上观看thenewboston)。我对 AndroidManifest.xml 很好奇。如果我理解正确的话,屏幕上显示的所有内容都是在该 xml 文件中定义的。但是,我的 java 游戏有自己的代码来创建棋盘:

 //game board
JFrame gameBoard = new JFrame();
gameBoard.setTitle("CrossGame");
gameBoard.setSize(400,400);

int numColors = 3;

//board grid
JPanel boardGrid = new JPanel(new GridLayout(gridSize, gridSize));

try {
  UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}
catch (Exception e) {
}
//A loop to add a new button to each section of the board grid.
for (int i = 0; i < gridSize; i++) {
  for (int j = 0; j < gridSize; j++) {

    gameButtons[i][j] = new JButton();
    gameButtons[i][j].addActionListener(new Listener());
    gameButtons[i][j].setBackground(colors[(int)(Math.random() * numColors)]);
    boardGrid.add(gameButtons[i][j]);

  }
}

//Adds the grid of buttons to the window.
gameBoard.add(boardGrid);
//Quits the program when the close window button is pressed.
gameBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameBoard.setVisible(true);

}

我正在 Mac 上编程,这就是为什么我在那里有 setLookAndFeel 的原因。所有这些按钮都必须在 XML 中定义吗?或者我必须修改这段代码吗?

最佳答案

Android 建议在 xml 中添加按钮以分离业务层和表示层。但这不是强制性的。因此,您可以像 java 应用程序一样在代码中完全修改它们

 For Example::
 for(int i::n)//depend upon your loop requirement
  {
      layout = (LinearLayout) findViewById(R.id.statsviewlayout);
      Button bi = new Button(this);
      bi.setText(R.string.button_back);
      bi.setLayoutParams(new LayoutParams(
      ViewGroup.LayoutParams.WRAP_CONTENT,
      ViewGroup.LayoutParams.WRAP_CONTENT));
      layout.addView(bi);
  }

关于java - 如果每次制作新游戏时都会在网格中生成这些按钮,我是否必须在 xml 中定义屏幕上的每个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14083789/

相关文章:

c# - “元素”是无效的 XmlNodeType

android - 在 android strings.xml 中引用字符串数组

java - 内部文本和子元素

java - 没有 WTP 的 Google Cloud SQL + JPA

java - 将 WAVE PCM 字节数组传递给 FFT 以进行音调检测

java - 如何从通知中打开 fragment ?

android - 具有以下 fragment 边缘 View 的应用栏

java - 这个算法的时间复杂度是O(N^2)吗?

Android:观察已删除线程的短信

java - 在 Android 中保存应用程序状态