RadioButton的drawableTop资源大小调整

RadioButton一般用的时候会伴随资源图片的使用,或左或右或上或下的,挺好用,但麻烦的是图片资源有多大它就给显示多大,XML文件还不能给调整:

XML布局:

  <RadioButton
            android:id="@+id/rb_a"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight=".2"
            android:button="@null"
            android:checked="true"
            android:drawableTop="@drawable/ic_launcher"
            android:gravity="bottom|center_horizontal"
            android:text="RB1" />

效果是这样的:
布局里面
差异表现的不是很明显,但是它们原来长啥样,现在就是啥样,假如每个图像像素大小不一,那么一点都说不上美观了,我们要求的是一片林子,鸟都一样,不能什么都有。

找了一下资料,解决办法如下:

rbs = new RadioButton[5];
//初始化控件,中间大个的,周围小弟
rbs[0] = (RadioButton) findViewById(R.id.rb_a);
rbs[1] = (RadioButton) findViewById(R.id.rb_b);
rbs[2] = (RadioButton) findViewById(R.id.rb_m);
rbs[3] = (RadioButton) findViewById(R.id.rb_c);
rbs[4] = (RadioButton) findViewById(R.id.rb_d);

for (RadioButton rb : rbs) {
  //挨着给每个RadioButton加入drawable限制边距以控制显示大小
  drs = rb.getCompoundDrawables();
  //获取drawables
  Rect r = new Rect(0, 0, drs[1].getMinimumWidth()*2/3, drs[1].getMinimumHeight()*2/3);
  //定义一个Rect边界
  drs[1].setBounds(r);
  //给drawable设置边界
  if (rb.getId() == R.id.rb_m) {
     r = new Rect(0, 0, drs[1].getMinimumWidth(), drs[1].getMinimumHeight());
     drs[1].setBounds(r);
  }

 rb.setCompoundDrawables(null,drs[1],null,null);
 //添加限制给控件
}

解释一下:
给控件起作用的是这个方法

public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom);

意思是给当前的控件的某个位置上的drawable设置边界限制,达到布局要求,参数依次是设置 上、下、左、右 四个位置的drawable边界大小,有的就设置,没的设置null,否则空指针异常。

按照Google的API解释:Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had setBounds(Rect) called。

可以看出这个方法的使用是有一个前提,必须在调用之前调用setBounds(Rect)。

Rect意思是矩形,用起来也简单,在绘图中设置画布大小都会用得到这个:

Rect r = new Rect(startX, startY, endX, endY);

这里的意思从坐标(startX, startY)到坐标(endX, endY)组成的矩形边界里面绘制图片。

效果如下,虽然有一个比较大,但是有个老大也是合理的么:
编辑之后

这样就可以按自己的想法来了,要瘦要胖,随你心情:
这里写图片描述

这里写图片描述

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值