源代码地址:http://download.youkuaiyun.com/download/wb935419471/9911736
RadioGroup实现单选并获得所选项值:
代码片段:
public class MainActivity extends Activity {
public TextView mTextView1;
public RadioGroup mRadioGroup1,mRadioGroup2;
public RadioButton mRadio1, mRadio2,mRadio3,mRadio4;
public Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 取得 TextView、RadioGroup、RadioButton对象
mTextView1 = (TextView) findViewById(R.id.myTextView);
submit = (Button) findViewById(R.id.submit);
mRadioGroup1 = (RadioGroup) findViewById(R.id.myRadioGroup);
mRadio1 = (RadioButton) findViewById(R.id.myRadioButton1);
mRadio2 = (RadioButton) findViewById(R.id.myRadioButton2);
mRadioGroup2 = (RadioGroup) findViewById(R.id.myRadioGroup2);
mRadio3 = (RadioButton) findViewById(R.id.myRadioButton3);
mRadio4 = (RadioButton) findViewById(R.id.myRadioButton4);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if(mTextView1.getText().toString().equals("")){
Toast toast = Toast.makeText(MainActivity.this, "mTextView1为空"+mTextView1.getText().toString(), Toast.LENGTH_SHORT);
toast.show();
}else{
Toast toast = Toast.makeText(MainActivity.this, "mTextView1选中的值为:"+mTextView1.getText().toString(), Toast.LENGTH_SHORT);
toast.show();
}
}
});
mRadioGroup1.setOnCheckedChangeListener(new OnMyManholeStateOneCheckedChangeListener());
mRadioGroup2.setOnCheckedChangeListener(new OnMyManholeStateTwoCheckedChangeListener());
}
private class OnMyManholeStateOneCheckedChangeListener implements
RadioGroup.OnCheckedChangeListener {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int position) {
switch (position) {
case R.id.myRadioButton1:
if (mRadio1.isChecked())
mRadioGroup2.clearCheck();//清除RadioGroup2的选中状态
mTextView1.setText(mRadio1.getText());
break;
case R.id.myRadioButton2:
if (mRadio2.isChecked())
mRadioGroup2.clearCheck();
mTextView1.setText(mRadio2.getText());
break;
default:
break;
}
}
}
private class OnMyManholeStateTwoCheckedChangeListener implements
RadioGroup.OnCheckedChangeListener {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int position) {
switch (position) {
case R.id.myRadioButton3:
if (mRadio3.isChecked())
mRadioGroup1.clearCheck();//清除RadioGroup1的选中状态
mTextView1.setText(mRadio3.getText());
break;
case R.id.myRadioButton4:
if (mRadio4.isChecked())
mRadioGroup1.clearCheck();
mTextView1.setText(mRadio4.getText());
break;
default:
break;
}
}
}
}
xml布局: