当我在 XML 布局文件中创建 RadioGroup 时,一切都很好,但是当我动态创建它时,RadioButtons 在选择另一个时不会取消选择:
这是代码:
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;
}
}
和布局文件:
<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>