废话不多说直接上代码:
写完子厚发现了一个问题 创建 的控件没有删除 所有又来补充
https://blog.csdn.net/sinat_41890480/article/details/108683192添加链接描述
<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="133dp"
android:layout_height="34dp"
android:layout_marginRight="20dp"
android:background="@drawable/de_ka_shap"
android:button="@null"
android:gravity="center"
android:text="金卡"
android:textColor="@color/colorJin"></RadioButton>
//创建动态数据 如果复用的 记得删除 已经创建的控件 deRgTaocan.removeAllViews();
ArrayList<String> mCourseList = new ArrayList<>(4);
mCourseList.add("套餐a");
mCourseList.add("套asdasd餐b");
//在创建之前删除掉
deRgTaocan.removeAllViews();
//for 添加
for (int i = 0; i < mCourseList.size(); i++) {
RadioButton radioButton = (RadioButton) View.inflate(this, R.layout.de_tc_rb, null);
radioButton.setText(mCourseList.get(i));
radioButton.setId(i);
radioButton.setTextColor(getResources().getColor(R.color.colorJin));
radioButton.setGravity(Gravity.CENTER);
//设置内边距 可以根据自己来 DensityUtil 工具类 自己找去
radioButton.setPadding(DensityUtil.dp2px(this, 20),
DensityUtil.dp2px(this, 5),
DensityUtil.dp2px(this, 20),
DensityUtil.dp2px(this, 5));
//设置宽度
RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//设置 meary 宽度
lp.setMargins(0, 0, DensityUtil.dp2px(this, 20), 0);
radioButton.setChecked(i == 0);
deRgTaocan.addView(radioButton, lp);
}
//点击事件
deRgTaocan.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case 0:
ToastUtils.show("" + mCourseList.get(checkedId));
break;
}
}
});