Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring button variables as an array with a for loop android

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));
            }
        });

    }
}
like image 850
Epcilon Avatar asked Dec 19 '12 09:12

Epcilon


1 Answers

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.

like image 137
Lawrence Choy Avatar answered Nov 13 '22 01:11

Lawrence Choy