1.获取RadioGroup控件:
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.myRadioGroup);
2.获取RadioButton控件:
RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
getCheckedRadioButtonId()必须在RadioButton选中之后调用,否则空指针异常。
3.获取选中的radio的值:
String text = radioButton.getText().toString();
4.为radioGroup添加监听事件,用来监听组件内部的事件响应:
1 2 3 4 5 6 7
| radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { selectRadioBtn(); } });
|
5.在onCreat中需要初始化上面的四条信息
6.整体的使用样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.waterselect);
getViews(); setListenerForView(); }
private void getViews(){ radioGroup = (RadioGroup)findViewById(R.id.isWaterByContent); }
private void setListenerForView(){ selectRadioBtn(); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { selectRadioBtn(); } }); }
private void selectRadioBtn(){ radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId()); waterIn = radioButton.getText().toString(); Log.i("radio", waterIn); }
|