1. 范例说明
- 今天介绍RadioGroup的组事件。RadioGroup可将各自不同的RadioButton设限于同一个Radio按钮组,同属于一个RadioGroup组里的按钮,只能做出单一选择(单选题)。
- 该范例首先设计一个TextView Widget,以及一个RadioGroup,并于该RadioGroup内放置两个RadioButton,默认为都不选择,在程序运行阶段,利用onCheckedChanged作为启动事件装置,让User在选择其中一个按钮时,显示被选择的内容,最后将RadioButton的选项文字显示于TextView中。
2. 运行结果
3. 编写代码
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /* 取得 TextView、RadioGroup、RadioButton对象 */ mTextView1 = (TextView) findViewById(R.id.myTextView); mRadioGroup1 = (RadioGroup) findViewById(R.id.myRadioGroup); mRadio1 = (RadioButton) findViewById(R.id.myRadioButton1); mRadio2 = (RadioButton) findViewById(R.id.myRadioButton2); /* RadioGroup用OnCheckedChangeListener来执行 */ mRadioGroup1.setOnCheckedChangeListener(mChangeRadio); } private RadioGroup.OnCheckedChangeListener mChangeRadio = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub if (checkedId == mRadio1.getId()) { /* 把mRadio1的内容传到mTextView1 */ mTextView1.setText(mRadio1.getText()); } else if (checkedId == mRadio2.getId()) { /* 把mRadio2的内容传到mTextView1 */ mTextView1.setText(mRadio2.getText()); } } };
4. 扩展学习与作业
RadioGroup单选按钮用法
http://www.eyeandroid.com/thread-10158-1-1.html
作业:请试着在其中加一个Button,作为清除RadioButton的选择状态
5.视频讲解