cannot becast to android.weidget.RadioGroup

今天做一个单选框的实验,大家都知道单选框必须归组才能实现单选,而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难道不是判断是否被选中吗?不知路过的大神能不能指点一二。

发布了3 篇原创文章 · 获赞 3 · 访问量 1087

猜你喜欢

转载自blog.csdn.net/qq_44927721/article/details/104281008