0

Hello i used a code to generate some buttons in a tablelayout. The buttons are generated by this layout, so none of them has an id yet. So here is my question. How can i give a specific button an id? (For example the button in the first row, second colum should have the id "button2")

public class MainActivity extends ActionBarActivity {

private static final int NUM_ROWS = 3;
private static final int NUM_COLS = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    populateButtons();
}


private void populateButtons() {
    TableLayout table = (TableLayout) findViewById(R.id.TableLayout);

    for (int row =0; row < NUM_ROWS; row++) {
        TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(new TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.MATCH_PARENT,
                1.0f));
        table.addView(tableRow);
        for (int col = 0; col < NUM_COLS; col++) {
            Button button = new Button(this);
            tableRow.addView(button);
    }
  } 
}
  • [setId()](http://developer.android.com/reference/android/view/View.html#setId(int)) but that takes an `int` so if you want a `String` then you could use [setTag()](http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object)) which takes an `Object` and reference it with `getTag()` – codeMagic Sep 10 '14 at 20:20
  • Take a look at this: http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts/14975498#14975498 – Loc Sep 10 '14 at 20:21

1 Answers1

0

You can use View.setId(), however I guess you don't have to find the Views by id because you already know them.

Diego Torres Milano
  • 57,580
  • 7
  • 101
  • 124
  • @DudeEffects, he meant that if you created the View, you can manipulate and store it as a View variable... No need for an id – LcSalazar Sep 10 '14 at 20:34