- 开发中业务需求总是千奇百怪(搞不懂产品经理脑壳里装的什么),有时候写布局的话可以直接在xml文件中完成,但是有时候业务需求,有些布局是是动态变化的,不是setvisibily就可完成的,这个时候就要考虑通过代码来添加子布局了。
常规使用的话:
直接在xml布局文件中写,button属性是为了去除系统自带的圆圈
<RadioGroup android:id="@+id/rg" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <RadioButton android:id="@+id/rb1" android:text="按键1" android:textColor="@color/teach_type_text_selector" android:background="@drawable/teach_type_rb_selector" android:button="@null" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioButton android:id="@+id/rb2" android:text="按键2" android:textColor="@color/teach_type_text_selector" android:background="@drawable/teach_type_rb_selector" android:button="@null" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RadioGroup>
上面使用的背景和text颜色选择器的代码我就不贴了,背景的话就是在res资源下的drawable目录中创建相应的选择器;颜色就是在res资源下的建个color目录,然后创建相应的选择器,
在代码中实现的话
- RadioButton mRb = new RadioButton(mContext);
- mRb.setTextColor(mContext.getResources().getColorStateList(R.color.teach_type_text_selector));
- mRb.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
- mRb.setBackground(ContextCompat.getDrawable(mContext, R.drawable.teach_type_rb_selector));
- rg.addView(mRb, mp);
上面最关键的是我转换color资源时使用的是Resources下的getColorStateList()方法,这样才有效果的