I am new user of android and making slide puzzle game and using eclipse.I made buttons in xml file.In java file I made an array of button type.Now my problem is how I add my buttons in array which I made in the xml file in table layout...
4 Answers
Each button should have a unique ID and you can use findViewById(R.id.ButtonX) to get the buttons. Say you have 5 buttons:
Button[] buttons = new Button[5];
buttons[0] = (Button)findViewById(R.id.Button0);
buttons[1] = (Button)findViewById(R.id.Button1);
buttons[2] = (Button)findViewById(R.id.Button2);
buttons[3] = (Button)findViewById(R.id.Button3);
buttons[4] = (Button)findViewById(R.id.Button4);
Of course the IDs have to match those in the XML. You could also use an ArrayList<Button> if you need to add or remove buttons from this array. Do note that adding or removing from the array will not add or remove them from the activity.
Comments
Create an activity. In Eclipse there should be 2 lower tabs with one letting you graphically edit the layout. Then all you have to do is link the Java buttons with the xml buttons.
1 Comment
You can try something like this. Assuming bi,b2 b3 are the button names in the XML
ArrayList<Button> bl = new ArrayList<Button>();
bl.add(new Button("b1"));
bl.add(new Button("b2"));
bl.add(new Button("b3"));
2 Comments
I understood that: You want to create dynamic button(You create button in java code not xml). Try that way:
Button btn1 = new Button(this);
Button btn2 = new Button(this);
Button btn3 = new Button(this);
//your table name : tbl
//you must create TableRow and add button to anyone row.And add row to table
TableRow row1 = new TableRow(this);
TableRow row2 = new TableRow(this);
row1.addView(btn1);
row2.addView(btn2);
row2.addView(btn3);
tbl.addView(row1);
tbl.addView(row2);