You have created TableRow
and CheckBox
you should set id pragmatically like this
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
row.setId(i);//i is a positive int value
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
row.setId(j);//j is a positive int value
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
You can check this SO question
int chkBoxId = 10;
int tableRowId = 100;
String texts[] = {"Text1", "Text2", "Text3", "Text4", "Text5"};
CheckBox[] chkBoxes;
private TableLayout tableLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_chk_box);
tableLayout = (TableLayout) findViewById(R.id.tableLayout);
chkBoxes = new CheckBox[texts.length];
for(int i = 0; i < 5; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
chkBoxes[i] = new CheckBox(this);
chkBoxes[i].setId(chkBoxId++);
row.setId(tableRowId);//tableRowId is a positive int value
chkBoxes[i].setText(texts[i]);
row.addView(chkBoxes[i]);
tableLayout.addView(row, i);
tableRowId++;
}
for (int i = 0; i < texts.length; i++) {
final int j = i;
chkBoxes[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked) {
int checkedId = chkBoxes[j].getId();
Toast.makeText(DynamicCheckBoxActivity.this,
String.valueOf(checkedId),
Toast.LENGTH_SHORT).show();
} else {
int unCheckedId = chkBoxes[j].getId();
System.out.println("Uncheck ===> " + String.valueOf(unCheckedId));
}
}
});
}
}