2
votes

This is a duplicate of: Android dynamically generated radio buttons not unchecking once setChecked programmatically

However in that question the answers didn't solve the question because all the code I added to try to solve the problem muddied the issue. In addition I have also applied several potential solutions below since then.

The problem is that if I check a RadioButton programmatically, it stays checked when I select another RadioButton in the same RadioGroup.

I have learned several potential solutions from Googling that I have applied but have not worked, such as:

  • Using RadioGroup.Check instead of RadioButton.setCheck
  • specifying each RadioButton's Id explicitly
  • Adding the RadioButton to the RadioGroup before checking it
  • Adding all the RadioButtons to the RadioGroup before checking one of them

despite all this, the RadioButton still stays checked when you click on another.

   private void PopulateAccessPoints(List<clsAccessPoint> accessPoints){
        try{
            rg = new RadioGroup(this);
            rlaAccessPoints.addView(rg);
            int i = 0;
            for (clsAccessPoint acp :  accessPoints) {
                i++;
                RadioButton rd = new RadioButton(this);
                rg.addView(rd);
                rd.setId(i);
                rd.setText(acp.ID + ": " + acp.Name);
            }

            rg.check(rg.getChildAt(1).getId());

            } catch (Exception ex) {
                ex.printStackTrace();
        }

Note: The RadioButton that should be checked will be determined dynamically, but I have hardcoded it as the above exhibits the same symptoms and is simpler.

I've spent several hours on this now so will appreciate any help for this apparently very simple problem!

1
I couldn't get this working so changed it to a group of buttons instead.james pearce

1 Answers

3
votes
            RadioButton rd = new RadioButton(this);
            rg.addView(rd);
            rd.setId(i);
            rd.setText(acp.ID + ": " + acp.Name);

try moving this code around to be like this:

            RadioButton rd = new RadioButton(this);
            rd.setId(i);
            rd.setText(acp.ID + ": " + acp.Name);
            rg.addView(rd);

setting the ids before you add it to the group?