0
你好,我使用了一个代码来生成tablelayout中的一些按钮。按钮由这个布局生成,所以它们都没有一个id。所以这是我的问题。我怎样才能给一个特定的按钮一个ID? (例如,第一行中的按钮,第二科拉姆应该有ID“按钮2”)如何给动态生成的按钮一个ID?
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))但需要一个'int',所以如果你想要一个'String',那么你可以使用[setTag()](http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object)),它接受一个'Object'并用'getTag引用它()' – codeMagic 2014-09-10 20:20:24
看看这个:http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts/14975498#14975498 – Loc 2014-09-10 20:21:03