我爲Java課程做了一個LightsOut遊戲,並作爲學習android的一種方法我試圖將它重建爲應用程序。我想優化我的Android應用程序
主要活動由一個togglebuttons網格組成。當一個按鈕被「檢查」時,它和它相鄰的按鈕被切換。當所有的按鈕都被關閉時,遊戲就會被取消。我已經做到了這一點,但代碼是可怕的。
我想通過製作一個二維數組的togglebuttons來清理代碼。我現在如何擁有它,我只是簡單地聲明每個按鈕。這會造成大量冗餘代碼,並且無法輕鬆縮放。
原來,在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是建設gamefield之前基於用戶輸入。這通過遍歷數組來初始化並檢查遊戲的狀態。我只是沒有找到一種方法來做到這一點與android。
那麼,有沒有辦法根據用戶輸入製作一個按鈕的數組/列表?
這裏的活動:
公共類LightsOutActivity擴展活動實現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中的唯一視圖是一個線性佈局。現在我已經硬編碼了數組的大小。
這就是我想要做的,是的。我的主要問題是初始化一組按鈕/ togglebuttons。它根本不適合我。也許我做錯了什麼,所以我希望有一個例子可以遵循。 – thethomasramsey
發佈你的Android代碼,也許我們會看到錯誤。 – C0deAttack
好的。我在上面的原始帖子中添加了onCreate()方法。 – thethomasramsey