Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RadioButtons Don't Properly Select/Deselect in Dynamically Created RadioGroup

When I create a RadioGroup in an XML layout file everything's fine, but when I create it dynamically the RadioButtons don't deselect when another is selected:

enter image description here

Here's the code:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);

    RadioButton radioButtonView = new RadioButton(this);
    radioButtonView.setText("RadioButton");
    radioGroup.addView(radioButtonView);

    RadioButton radioButtonView2 = new RadioButton(this);
    radioButtonView2.setText("RadioButton2");
    radioGroup.addView(radioButtonView2);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

And the layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" >
</RadioGroup>
</RelativeLayout>
like image 696
Jonathan Avatar asked Feb 18 '23 09:02

Jonathan


1 Answers

You need to set some sort of ID for your radio button, as such:

int idRadio = <some number>;
radioButtonView.setId(idRadio++);
radioButtonView2.setId(idRadio++);

Once they have distinct IDs, it should work. Just make sure the IDs don't collide with any existing graphical element, and is not zero (go to your "gen" folder and look at R.java for the other element IDs).

like image 76
Stephen Wylie Avatar answered Apr 29 '23 05:04

Stephen Wylie