在开发中我们经常用到TextView、Button、RadioButton这三个控件,很多时候我们需要文字和图片一起出现,很多应用的底部的导航栏用RadioGroup来实现切换的功能。这时候我们要用RadioButton的drawableTop、drawableLeft、drawableRight、drawableBottom四个属性值,来设定文字对应方向的图片,但是却没有设置图片大小的属性值。
要想设置这些图片的大小其实很简单,我们要了解一下下面几个方法:
getCompoundDrawables() 该方法返回包含控件左,上,右,下四个位置的Drawable的数组
setBounds(left,top,right,bottom)指定drawable的边界
setCompoundDrawables(drawableLeft, drawableTop, drawableRight, drawableBottom)设置控件左,上,右,下四个位置的Drawable
Button、RadioButton其实都是TextView的子类,这三个方法都是TextView里的方法
所以流程就是,我们首先拿到控件上面位置的drawable,然后给指定drawable的边界,最后再把drawable设置进去
来看下面的例子
代码如下
/** * 设置底部按钮 */ public void initButton() { main_home = (RadioButton) findViewById(R.id.main_bottom_home); main_notice = (RadioButton) findViewById(R.id.main_bottom_notice); main_cart = (RadioButton) findViewById(R.id.main_bottom_cart); main_my = (RadioButton) findViewById(R.id.main_bottom_my); RadioButton[] rbs = {main_home, main_notice, main_cart, main_my}; for (RadioButton rb : rbs) { //挨着给每个RadioButton加入drawable限制边距以控制显示大小 Drawable[] drs = rb.getCompoundDrawables(); //获取drawables Rect r = new Rect(0, 0, drs[1].getMinimumWidth() / 3, drs[1].getMinimumHeight() / 3); //定义一个Rect边界 drs[1].setBounds(r); rb.setCompoundDrawables(null, drs[1], null, null); } }