Declaring button variables as an array with a for loop android

android, arrays, for-loop, java, variables

Solution

I would do the following:

private static final int[] idArray = {R.id.bt0, R.id.bt1, R.id.bt2, R.id.bt3, R.id.bt4, R.id.bt5};

private Button[] bt = new Button[idArray.length];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_layout);

    for (int i=0; i<idArray.length; i++) {
        final int b = i;
        bt [b] = (Button)findViewById(idArray[b]); // Fetch the view id from array
        bt [b].setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent myIntent = new Intent(Start.this, MainActivity.class);
                myIntent.putExtra("players", b);
                startActivity(myIntent);

                //startActivity(new Intent(Start.this, MainActivity.class));
            }
        });

    }
}

If you want to add or remove buttons, just add it to `idArray` and all other things are dynamic already.

Problem

I managed to create buttons in a for loop and saw no reason why not to declare my varibles inside it too. Unfortunately eclipse only identifies the "bt" and doesn't want to replace my [i] with the number it represents in the loop and as a result find the correct id in my layout. Any thoughts on how to make this work? I'm also greatful for any other solution as beatiful as mine, which doesn't work ;) ``` Button [] bt = new Button[6]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_layout); bt[0] = (Button) findViewById(R.id.bt0); bt[1] = (Button) findViewById(R.id.bt1);//This is what i'm trying to replace bt[2] = (Button) findViewById(R.id.bt2); bt[3] = (Button) findViewById(R.id.bt3); bt[4] = (Button) findViewById(R.id.bt4); bt[5] = (Button) findViewById(R.id.bt5); for (int i=0; i<6; i++) { final int b = i; bt [i] = (Button)findViewById(R.id.bt[i]); <----//Whith this bt [i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(Start.this, MainActivity.class); myIntent.putExtra("players", b); startActivity(myIntent); //startActivity(new Intent(Start.this, MainActivity.class)); } }); } } ```

Original source

Related problems