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

当业务需求需要动态改变布局时,单纯使用XML无法满足。本文介绍如何通过代码解决RadioButton的颜色选择器无效问题,包括如何设置背景和文字颜色选择器,并在res资源目录下创建相关选择器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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()方法,这样才有效果的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值