Java – Set the ID for each dynamically created View for each loop – android

Set the ID for each dynamically created View for each loop – android… here is a solution to the problem.

Set the ID for each dynamically created View for each loop – android

I use for: Each loop iterates over the ArrayList to dynamically add an unknown number of views to the TableLayout.

When I try to set a unique ID for each View, each View ends up with 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 distinguish between Views when using OnClickListener.

public void onCheckBoxClick(Integer id) {

Log.d("ID", id);
}

Each checkbox has the same ID, which is always the last one set.

Solution

The first View.generateViewId() (API level > 17) creates a unique ID for your View.

Then set the generated ID using setId().

Related Problems and Solutions