I'm adding an unknown number of views to a TableLayout dynamically by iterating over an ArrayList with a for..each loop.
When I try to set unique ids to each view, each view ends up having the same ID.
TableLayout Table = findViewById(R.id.table);
idCounter = 0;
for (String string: array) {
TableRow row = new TableRow(this);
// adds id to table
TextView serialText = new TextView(this);
serialText.setText(string);
row.addView(serialText);
serialText.setId(idCounter);
idCounter ++;
// first checkbox
CheckBox firstCheckbox= new CheckBox(this);
row.addView(firstcheckbox);
firstcheckbox.setId(idCounter);
idCounter ++;
firstCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onCheckBoxClick(idCounter);
}
});
// second checkbox
CheckBox secondCheckbox= new CheckBox(this);
row.addView(secondCheckbox);
secondCheckbox.setId(idCounter);
idCounter ++;
secondCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onCheckBoxClick(idCounter);
}
});
// third checkbox
CheckBox thirdCheckbox= new CheckBox(this);
row.addView(thirdCheckbox);
thirdCheckbox.setId(idCounter);
idCounter ++;
thirdCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onCheckBoxClick(idCounter);
}
});
// add row to table
Table.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
I need each view to have a unique ID so I can differentiate between the views when an OnClickListener is used.
public void onCheckBoxClick(Integer id) {
Log.d("ID", id);
}
Each checkbox has the same ID, it's always the last one that has been set.
First View.generateViewId() (API level > 17) will create an unique id for your view.
Then use setId() to set that generated id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With