android上的动态表单可能非常混乱,我遇到了这样一种特定的情况:我通过RadioGroup
和AppCompatRadioButton
创建选项列表,其中checkedd与动态RadioGroup
无关:
String [] options = new String[] {"Option 1", "Option 2", "Option 3", "Option 4"};
private void buildDynamicRadioGroup(){
final LinearLayout linearLayout = new LinearLayout(MyActivity.class);
final RadioGroup radioGroup = new RadioGroup(MyActivity.class);
for(String option: options){
final AppCompatRadioButton radioButton = new AppCompatRadioButton(MyActivity.class);
radioButton.setText(option);
radioGroup.addView(radioButton);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("Checked Group Count", group.getChildCount()); // this is always 4
Log.d("Option Id", checkedId); // this prints correctly the first time
}
});
linearLayout.addView(radioGroup);
}
对
buildDynamicRadioGroup()
的第一次调用看起来没问题,但是对方法的每个附加调用(即n>1),checkedId
反映的是通过调用此方法生成的AppCompatRadioButton
的总数,而不是所讨论的checkedId
的实际RadioGroup
。例如:对方法的第二次调用将打印4,如果在
RadioButton
s的2组中选择了2项,则打印6,因为有6个AppCompatRadioButton
s任何人都知道如何处理这个问题,所以我只能在
checkedId
上下文中获取RadioGroup
? 最佳答案
就在今天,我遇到了同样的问题,在寻找解决方案时发现了你的问题。唯一的区别是,我正在从xml资源加载RadioButtons
。
对我来说,问题是所有单选按钮都有相同的id,RadioGroup
在切换单选按钮的状态时使用这些id。
我可以通过在将单选按钮添加到RadioGroup
之前更改其ID来解决问题。因此,我只是添加一个随机的正id:
private View createViewForButton(
final Context context,
final Option radioButton) {
final View view =
getLayoutInflater(context).inflate(R.layout.form_radiobutton, null);
final RadioButton label = (RadioButton) view.findViewById(R.id.label_view);
label.setText(radioButton.getValue());
makeButtonWorkingInRadioGroup(view);
return view;
}
private void makeButtonWorkingInRadioGroup(final View view) {
// The radio group requires all RadioButtons to have different IDs to
// work correctly. This wouldn't work else as we are loading all
// RadioButtons from the same XML file having the same ID definition.
view.setId(View.generateViewId());
}
确保您设置的ID为正。用阴性的身份证也不行。
关于android - RadioGroup onCheckChanged(RadioGroup radioGroup,int CheckedId)在动态表单中无法正常使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32509267/