I’m developer an Android 3.1 and above application.
I’m developer a dynamic form generator, and I need to add programatically a lot of check boxes.
Forms will be tables with a question on their first column, and the others columns will have check boxes.
This is a piece of code where I add check boxes:
int optionsTotalNum = this.calculateColumsForBlock(block);
QuestionsGroup qGroup = block.getQuestionsGroup();
for(int z = 0; z < qGroup.getQuestions().size(); z++)
{
tableRow = new TableRow(this);
Question q = qGroup.getQuestions().get(new Integer(z));
params = new LayoutParams(this.optionWidth, this.rowHeight);
params.column = 0;
TextView optionName = new TextView(this);
optionName.setText(q.getQuestionText().toUpperCase());
optionName.setGravity(Gravity.CENTER);
optionName.setLayoutParams(params);
tableRow.addView(optionName);
for (int index = 1; i < optionsTotalNum; i++)
{
params.column = index;
CheckBox check = new CheckBox(this);
int id = ((z + 1) * 100) + index;
check.setId(id);
check.setLayoutParams(params);
tableRow.addView(check);
}
table.addView(tableRow, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
this.rowHeight));
}
I use int id = ((z + 1) * 100) + index; to create ids dynamically but I’m not sure if I will repeat and Id. In other words, I’m not sure if I will have two views with the same ids. I know that all check boxes will have different IDs, but I will have TextViews, and a TableLayout and TableRows and I don’t know if they could have an ID that is used on a CheckBox.
What happen with findViewById() if there are two views with the same ID?
Can we have two or more views with the same ID on a same ContentView?
Is there any better method to identify all check boxes uniquely?
Well since you are adding it at runtime.. you don’t have to set an id.. you can keep all of them in some Collection which maintains insertion order and access them directly…
if you want to continue with same idea.. then don’t do any complex stuff here.. just keep a static counter at class level.. set it as id and then increment it…