Note that there are some explanatory texts on larger screens.

plurals
  1. POI am trying to optimize my android application
    text
    copied!<p>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.</p> <p>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 off the game is won. I have made it work to this point but the code is horrendous.</p> <p>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.</p> <p>Originally, in java I did this:</p> <pre><code> buttons = new LightButton[xCor][xCor]; for (int x = 0; x &lt; xCor; x++) { for (int y = 0; y &lt; xCor; y++) { buttons[x][y] = new LightButton(this, x, y); panel.add(buttons[x][y]); } } </code></pre> <p>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.</p> <p>So, is there a way to make an array/list of togglebuttons based on user input?</p> <p>Here is the activity:</p> <p>public class LightsOutActivity extends Activity implements OnClickListener {</p> <pre><code>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 &lt; 4; x++) { for (int y = 0; y &lt; 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)); } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload