首先在布局中设置你想要的布局效果
以我自己为例:
<?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:contentDescription="作者"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroup"
>
<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="李清照"/>
<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>
<TextView
android:id="@+id/tvSex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="作者是:"
/>
</LinearLayout>
然后在Java代码中写自己的程序
public class RadiioGroupActiviy extends Activity {
TextView tv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup_main);
//根据ID找到该文本控件
tv = (TextView)this.findViewById(R.id.tvSex);
//根据ID找到RadioGroup实例
RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
//绑定一个匿名监听器
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int postion) {
// TODO Auto-generated method stub
//获取变更后的选中项的ID
int radioButtonId = arg0.getCheckedRadioButtonId();
//根据ID获取RadioButton的实例
RadioButton rb = (RadioButton)findViewById(radioButtonId);
//更新文本内容,以符合选中项
if (rb.getText().equals("贺知章")){
Toast.makeText(RadiioGroupActiviy.this, "选择正确",0 ).show();
}
else{
Toast.makeText(RadiioGroupActiviy.this, "错误", 0).show();
}
tv.setText("您的选择是:" + rb.getText());
}
});
}
}