项目场景:
RadioGroup动态生成RadioButton,设置默认选中第一个问题描述:
RadioGroup.check(1)时,有些场景会默认选中,有些则不会选中,跟踪查看时,RadioGroup的checkId确实是1动态生成RadioButton
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("ResourceType")
public static void dynamicGenerationRadioButton(Activity activity, String[] data, RadioGroup group,int btnBg,int textColor){
for (String title:data){
RadioButton tempButton = new RadioButton(activity);
tempButton.setBackground(activity.getResources().getDrawable(btnBg));
tempButton.setButtonDrawable(0); // 设置按钮的样式 取消圆圈
tempButton.setPadding(30, 0, 30, 0); // 设置文字距离按钮四周的距离
tempButton.setText(title);
tempButton.setTextSize(16);
ColorStateList colorStateList=activity.getColorStateList(textColor); //设置选中RadioButton效果
tempButton.setTextColor(colorStateList);
group.addView(tempButton);
}
group.check(1);
}
原因分析:
查找失效场景:当=若当前页面涉及两个或以上RadioGroup动态生成RadioButton时;分析:
1、通过RadioGroup的checkid为1,可以确定此时check是正确的,但未产生效果,此时初步推断是当前的RadioGroup的第一个RadioButton的id不为1;
2、再结合问题场景,两个RadioGroup动态生成RadioButton时,第二个RadioGroup的第一个RadioButton的id可能与前一个RadioGroup生成的RadioButton ID有关。
解决方案:
1、在动态生成时,获取第一个RadioButton的ID,此时发现该ID不为1,即验证了第一个猜想;
2、经查证此时ID为10,这时发现上个RadioGroup生成的RadioButton的个数为9,即第二个猜想,第二个问题RadioGroup的RadioButton的id是在前一个动态生成的ID数上进行累加得到的。
正确生成代码:
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("ResourceType")
public static void dynamicGenerationRadioButton(Activity activity, String[] data, RadioGroup group,int btnBg,int textColor){
for (int i=0;i<data.length;i++){
RadioButton tempButton = new RadioButton(activity);
tempButton.setBackground(activity.getResources().getDrawable(btnBg));
tempButton.setButtonDrawable(0); // 设置按钮的样式 取消圆圈
tempButton.setPadding(30, 0, 30, 0); // 设置文字距离按钮四周的距离
tempButton.setText(data[i]);
tempButton.setTextSize(16);
ColorStateList colorStateList=activity.getColorStateList(textColor);
tempButton.setTextColor(colorStateList);
group.addView(tempButton);
if (i==0){
group.check(tempButton.getId()); //获取第一个生成RadioButton的ID,给graoup的check
}
}
}