RadioGroup动态生成RadioButton设置默认选择偶尔失效

项目场景:

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
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值