1.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="性别:" />
<RadioGroup android:id="@+id/sex" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:checkedButton="@+id/man">
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="男"
android:id="@id/man"
android:checked="true"></RadioButton>
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="女"></RadioButton>
</RadioGroup>
<Button android:id="@+id/button" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="选择性别"></Button>
</LinearLayout>
2.监听事件
public class Main extends Activity {
private RadioGroup group;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
group = (RadioGroup) this.findViewById(R.id.sex);
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int len = group.getChildCount();
String msgString = "";
for (int i = 0; i < len; i++) {
RadioButton radioButton = (RadioButton) group.getChildAt(i);
if (radioButton.isChecked()) {
msgString = radioButton.getText().toString();
break;
}
}
Toast.makeText(Main.this, msgString, 1).show();
}
});
}
}
3.运行结果显示