RadioButton必须在RadioGroup中
<RadioGroup
android:id="@+id/rg"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女" />
</RadioGroup>
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择" />
public class RadiobuttonActivity extends Activity implements OnClickListener {
private RadioGroup rg;
private Button bt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rg = (RadioGroup) this.findViewById(R.id.rg);
bt = (Button) this.findViewById(R.id.bt);
bt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int len = rg.getChildCount();// 得到RadioGroup中的RadioButton个数。
String s = "";
for (int i = 0; i < len; i++) {
RadioButton rb = (RadioButton) rg.getChildAt(i);//得到对应的RadioButton
s = rb.getText().toString();
Toast.makeText(getApplicationContext(), s, 1).show();
}
}
}