今天做一个单选框的实验,大家都知道单选框必须归组才能实现单选,而RadioGroup有个方法getChildAt()得到组内的子控件。因此我打算运用一下这个方法。
目的:通过getChildAt()的到组内控件,再判断该控件是否被选中。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
confirm =(Button)findViewById(R.id.button1);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer sBuffer = new StringBuffer();
RadioButton rButton;
for(int i =0;i<radioGroup.getChildCount();i++) {
rButton =(RadioButton)radioGroup.getChildAt(i);
if(radioGroup.getChildAt(i).isSelected()) { //注意这里if语句的判断条件
sBuffer.append(rButton.getText().toString() + ";");
}
Toast.makeText(MainActivity .this, sBuffer.substring(0, sBuffer.length()-1), Toast.LENGTH_SHORT).show();
}
}
});
写完这段代码后激动的运行了下,结果出现程序不能运行的错误,log如下
思来想去不知道哪里有问题,我猜测是if语句的判断条件有问题,但是getChildAt()返回的是view类,而view类的isSelected难道不是判断是否被选中吗?不知路过的大神能不能指点一二。