I made a LightsOut game for a java course and as a way to learn android I am trying to rebuild it as an application.
The main activity consists of a grid of togglebuttons. When a button is "checked" it and its adjacent buttons are toggled. When all of the buttons are toggled o开发者_如何学运维ff the game is won. I have made it work to this point but the code is horrendous.
I would like to clean the code up by making a two-dimensional array of togglebuttons. How I have it at the moment I simply declare each button individually. This makes for large blocks of redundant code and with no easy way to scale.
Originally, in java I did this:
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]);
}
}
Where xCor was based on user input prior to construction of the gamefield. This made initializing and checking the status of the game easy by traversing the array. I simply have not found a way to do this with android.
So, is there a way to make an array/list of togglebuttons based on user input?
Here is the activity:
public class LightsOutActivity extends Activity implements 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));
}
The immediately results in a force close. The only view in R.layout.main is a linearlayout. For now I've hard coded the array size.
Can't you take user input from a EditText view? Then you can initialize your array with that input.
精彩评论