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:
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>
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).
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