Lara
Lara

Reputation: 172

Array of Buttons in Java

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 !

Upvotes: 0

Views: 131

Answers (4)

tanou
tanou

Reputation: 1093

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

Upvotes: 0

Harshal Benake
Harshal Benake

Reputation: 2401

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

Upvotes: 0

Kiruba Karan
Kiruba Karan

Reputation: 39

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];

Upvotes: 1

Alexander
Alexander

Reputation: 48252

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

Upvotes: 6

Related Questions