RadioButton动态添加drawable

本文介绍如何在XML布局文件及代码中为RadioButton控件添加图标,详细讲解了使用Drawable.setBounds()设置图标尺寸的方法。

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

在xml中实现的效果,在代码中都可实现,但有时候对api不太了解的话就会出现很多问题,


如果让你在xml文件中给radiobutton控件添加drawable,你肯定觉得很简单


<RadioGroup
    android:id="@+id/rg"
    android:orientation="horizontal"
    android:layout_centerInParent="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RadioButton
        android:background="@drawable/rb_selector"
        android:text="按钮"
        android:button="@null"
        android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RadioButton
        android:id="@+id/radioButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rb_selector"
        android:button="@null"
        android:drawableRight="@drawable/hot"
        android:padding="10dp"
        android:text="按钮" />

</RadioGroup>

通过设置相应的drawableXXX属性即可

但通过代码实现的话就要注意了

  1. rgGroup = (RadioGroup)findViewById(R.id.re_group);       
  2. rbWeiHui = (RadioButton)findViewById(R.id.rb_wei_hui);       
  3. rbAdd = (RadioButton)findViewById(R.id.rb_add);       
  4. rbMine = (RadioButton)findViewById(R.id.rb_mine);       
  5. //定义底部标签图片大小        
  6. Drawable drawableWeiHui =getResources().getDrawable(R.drawable.btn_tab_wei_hui_selector);       
  7. drawableWeiHui.setBounds(0, 0, 69, 69);//第一0是距左右边距离,第二0是距上下边距离,第三69长度,第四宽度       
  8. rbWeiHui.setCompoundDrawables(null,drawableWeiHui, null, null);//只放上面       
  9. Drawable drawableAdd =getResources().getDrawable(R.drawable.btn_tab_add_selector);       
  10. drawableAdd.setBounds(0, 0, 168, 120);       
  11. rbAdd.setCompoundDrawables(drawableAdd,null, null, null);       
  12. Drawable drawableRight = getResources().getDrawable(R.drawable.btn_tab_mine_selector);       
  13. drawableRight.setBounds(0, 0, 69, 69);       
  14. rbMine.setCompoundDrawables(null,drawableRight, null, null);       
  15. //初始化底部标签       
  16. rgGroup.check(R.id.rb_wei_hui);// 默认勾选首页,初始化时候让首页默认勾选

这里需要特别注意了,api文档说明了在使用setCompoundDrawables方法前,需要用Drawable.setBounds()方法来为Drawable图片设置边界,即要显示的大小。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值