动态添加RadioButton

1、问题

在添加数量不确定的RadionButton,或者需要对RadioButton样式化(如添加selector等)时可以考虑动态添加RadionButton。

2、具体代码

for (int i = 0; i < mCourseList.size(); i++) {
    RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.radio_button, null);
    radioButton.setText(mCourseList.get(i));
    radioButton.setId(i);
    RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    if (i != 0) {
        lp.leftMargin = DensityUtil.dp2px(30);
    }
    radioButton.setChecked(i == 0);
    mCourseRadioGroup.addView(radioButton, lp);
}

3、注意事项

在动态添加时需要主动设置id和check状态。否则会出现多选或者无法选中的情况。

猜你喜欢

转载自blog.csdn.net/honeysx/article/details/80474892
今日推荐