MainActivity中的代码:
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)this.findViewById(R.id.tvSex);
RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int radioButtonId = arg0.getCheckedRadioButtonId();
RadioButton rb = (RadioButton)MyActiviy.this.findViewById(radioButtonId);
tv.setText("您的性别是:" + rb.getText());
}
});
}
xml布局文件中的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请选择您的性别:"
/>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="性别" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男" >
</RadioButton>
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女" >
</RadioButton>
</RadioGroup>
<TextView
android:id="@+id/tvSex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="您的性别是:男"
/>
</LinearLayout>
原文地址