第一种:
private RadioGroup group;
private RadioButton rb1 ;
private RadioButton rb2 ;
group = (RadioGroup) findViewById(R.id.group);
this.rb1 = (RadioButton) this.findViewById(R.id.button1) ;
this.rb2 = (RadioButton) this.findViewById(R.id.button2) ;
// 单选按钮组监听事件
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// 根据ID判断选择的按钮
if (checkedId == R.id.button1) {
textView.setText("Android新手");
rb1.setText("我是1") ;
String msg = rb1.getText().toString() ; //获取单独的radioButton的按钮
rb2.setText(msg) ;
} else {
textView.setText("Android高手");
rb2.setText("我是2") ;
} } });
第二种:
//对控件对象进行声明 private RadioGroup genderGroup=null; private RadioButton femaleRadioButton=null; private RadioButton maleRadioButton=null; private EditText editText1=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //通过控件的ID来得到代表控件的对象 genderGroup=(RadioGroup)findViewById(R.id.genderGroup); femaleRadioButton=(RadioButton)findViewById(R.id.femaleButton); maleRadioButton=(RadioButton)findViewById(R.id.maleButton); editText1=(EditText)findViewById(R.id.editText1); //给RadioGroup设置事件监听 genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub if(checkedId==femaleRadioButton.getId()){ editText1.setText("女性"); }else if(checkedId==maleRadioButton.getId()){ editText1.setText("男性"); } } });
第三种:
TextView tv = null;//根据不同选项所要变更的文本控件@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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 arg1) {
// TODO Auto-generated method stub
//获取变更后的选中项的ID
int radioButtonId = arg0.getCheckedRadioButtonId();
//根据ID获取RadioButton的实例
RadioButton rb = (RadioButton)MyActiviy.this.findViewById(radioButtonId);
//更新文本内容,以符合选中项
tv.setText("您的性别是:" + rb.getText());
}
});
}