问题
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>
回答1:
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).
回答2:
Related question how to uncheck the radio button in android.
Try radioButtonView.setChecked(false);
来源:https://stackoverflow.com/questions/13558045/radiobuttons-dont-properly-select-deselect-in-dynamically-created-radiogroup