0

您好,我使用代码在表格布局中生成一些按钮。这些按钮是由这个布局生成的,所以它们都没有一个 id。所以这是我的问题。我怎样才能给一个特定的按钮一个ID?(例如第一行的按钮,第二列的 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);
    }
  } 
}
4

1 回答 1

0

您可以使用View.setId(),但是我想您不必按 id 查找视图,因为您已经知道它们。

于 2014-09-10T20:21:03.770 回答