解决代码中写radiobutton颜色选择器无效问题

来源:互联网 发布:bilibili客户端mac 编辑:程序博客网 时间:2024/04/27 21:33
  1. 开发中业务需求总是千奇百怪(搞不懂产品经理脑壳里装的什么),有时候写布局的话可以直接在xml文件中完成,但是有时候业务需求,有些布局是是动态变化的,不是setvisibily就可完成的,这个时候就要考虑通过代码来添加子布局了。
今天开发时遇到在代码中添加RadioButton并且要设置颜色选择器

常规使用的话:

直接在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目录,然后创建相应的选择器,


在代码中实现的话

  1. RadioButton mRb = new RadioButton(mContext);
  2. mRb.setTextColor(mContext.getResources().getColorStateList(R.color.teach_type_text_selector));
  3. mRb.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
  4. mRb.setBackground(ContextCompat.getDrawable(mContext, R.drawable.teach_type_rb_selector));
  5. rg.addView(mRb, mp);
上面最关键的是我转换color资源时使用的是Resources下的getColorStateList()方法,这样才有效果的

0 0
原创粉丝点击