main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/genderRg"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/maleRb" android:text="@string/maleTxt"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/femaleRb" android:text="@string/femaleTxt"/> </RadioGroup> </LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">性别选择</string> <string name="app_name">RadioButton</string> <string name="maleTxt">男</string> <string name="femaleTxt">女</string> </resources>
RadioButtonActivity.java
package com.qianlong.activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class RadioButtonActivity extends Activity {
private RadioGroup genderRg;
private RadioButton maleRb;
private RadioButton femaleRb;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.genderRg = (RadioGroup) this.findViewById(R.id.genderRg);
this.maleRb = (RadioButton) this.findViewById(R.id.maleRb);
this.femaleRb = (RadioButton) this.findViewById(R.id.femaleRb);
this.genderRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int maleRbId = RadioButtonActivity.this.maleRb.getId();
int femaleRbId = RadioButtonActivity.this.femaleRb.getId();
String youchecked = "您选择了:";
if(maleRbId == checkedId) {
youchecked += "男";
Toast.makeText(RadioButtonActivity.this, youchecked, Toast.LENGTH_SHORT).show();
}
if(femaleRbId == checkedId) {
youchecked += "女";
Toast.makeText(RadioButtonActivity.this, youchecked, Toast.LENGTH_SHORT).show();
}
}
});
}
}