RadioButton的drawableTop资源大小调整

来源:互联网 发布:淘宝售前客服流程视频 编辑:程序博客网 时间:2024/06/10 00:23

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)组成的矩形边界里面绘制图片。

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

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

这里写图片描述

1 0