2

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...

1
  • 1
    You should read the docs if you haven't developer.android Commented Nov 6, 2012 at 15:10

4 Answers 4

3

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.

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

Comments

1

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

The question states the buttons are already made in the XML file.
1

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

Button doesn't have a constructor that takes a string.
sorry missed that,need to use something like this(Button) findViewById(R.id.button1);
1

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

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.