0

I tried to make an array of buttons:

Button[] buttonlist = new Button[2];

Button btn1;
Button btn2;
Button btn3;
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn3 = (Button) findViewById(R.id.button3);

buttonlist[0] = btn1;
buttonlist[1] = btn2;
buttonlist[2] = btn3;

What did I do wrong here ? Thanks !

1
  • The way you use it defeats the point of storing them into an array Commented Mar 2, 2014 at 12:33

4 Answers 4

6

Must be Button[] buttonlist = new Button[3];

Sign up to request clarification or add additional context in comments.

2 Comments

I thought counting of arrays starts at 0 ?
Yes, but you have 3 buttons, not 2. When defining array you specify its size therefore 3. And having declared it you have button[0], [1] and [2]
1

Array index in java doesnt start with 1...It starts with 0...This was the mistake you have done.. you must remove this line

buttonlist[2] = btn3;

or add this line

Button[] buttonlist = new Button[3];

Comments

0

try this out.Hope it works :)

Button btn[] = new Button[2];
for (int i=0;i<2;i++){
    btn[i] = new Button(this); // initialize it
    btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
    btn[i].setText(name[i]);
    layout.addView(btn[i]);
}

Comments

0

The answer above is fully right, but I just wanted to add that you could avoid using temporary variables and directly assign your button in your array:

Button[] buttonlist = new Button[3];

buttonlist[0] = (Button) findViewById(R.id.button1);
buttonlist[1] = (Button) findViewById(R.id.button2);
buttonlist[2] = (Button) findViewById(R.id.button3);

In my opinion, that's more readable ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.