我需要动态地将RadioButtons添加到应用程序中,当我向布局添加按钮或组时,它可以完美地运行。但是当我尝试将RadioButtons添加到RadioGroup应用程序崩溃时出现强制转换异常: android.widget.RadioButton无法强制转换为android.widget.LinearLayout
我用过这篇文章作为参考: Creating RadioButtons programmatically。 它必须是非常基本的东西,但我已经玩了一段时间了,所以有点不知所措,试图解决它。
这是我的代码:
protected void addRadioButtons(LinearLayout layout, String switchOptions){
String[] optionsArray = switchOptions.split(",");
int numberOfOptions = optionsArray.length;
RadioButton[] radioButton = new RadioButton[numberOfOptions];
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
LayoutParams radioGroupParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(radioGroupParams);
//layout.addView(radioGroup);
for (int i = 0; i<numberOfOptions;i++){
radioButton[i] = new RadioButton(this);
radioButton[i].setText(i + "");
radioGroup.addView(radioButton[i]);
}
layout.addView(radioGroup);
}