【发布时间】:2011-09-14 21:05:21
【问题描述】:
我为 Java 课程制作了 LightsOut 游戏,作为学习 android 的一种方式,我正在尝试将其重新构建为应用程序。
主要活动由一个切换按钮网格组成。当一个按钮被“选中”时,它和它的相邻按钮都会被切换。当所有按钮都关闭时,游戏就获胜了。我已经做到了这一点,但代码太可怕了。
我想通过制作一个二维切换按钮数组来清理代码。我现在是如何拥有它的,我只是单独声明每个按钮。这会产生大量冗余代码,并且无法轻松扩展。
原来,在java中我是这样做的:
buttons = new LightButton[xCor][xCor];
for (int x = 0; x < xCor; x++) {
for (int y = 0; y < xCor; y++) {
buttons[x][y] = new LightButton(this, x, y);
panel.add(buttons[x][y]);
}
}
xCor 在构建游戏场之前基于用户输入。通过遍历数组,这使得初始化和检查游戏状态变得容易。我只是还没有找到用 android 做到这一点的方法。
那么,有没有办法根据用户输入制作一个切换按钮的数组/列表?
这是活动:
公共类 LightsOutActivity 扩展 Activity 实现 OnClickListener {
protected ToggleButton[][] buttonArray;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buttonArray = new ToggleButton[4][4];
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
buttonArray[x][y] = new ToggleButton(this);
LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f);
buttonArray[x][y].setLayoutParams(params);
((ViewGroup) findViewById(R.layout.main)).addView(buttonArray[x][y]);
}
}
setContentView(findViewById(R.layout.main));
}
立即导致强制关闭。 R.layout.main 中唯一的视图是线性布局。现在我已经硬编码了数组大小。
【问题讨论】:
标签: java android optimization multidimensional-array togglebutton