Android设置drawableTop图片大小

在开发中我们经常用到TextView、Button、RadioButton这三个控件,很多时候我们需要文字和图片一起出现,很多应用的底部的导航栏用RadioGroup来实现切换的功能,例如QQ等等,这时候我们要用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设置进去

这个例子是一个RadioGroup里有五个RadioButton,分别有drawableTop图片

    /**
     * 设置底部按钮
     */
    public void initButton(){
        for (int i = 0; i < radioIds.length; i++) {//循环

            drawables = radioBtns[i].getCompoundDrawables();//通过RadioButton的getCompoundDrawables()方法,拿到图片的drawables,分别是左上右下的图片

            switch (i) {//为每一个drawableTop设置属性setBounds(left,top,right,bottom)
            case 0:
                drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x18),
                        getResources().getDimensionPixelSize(R.dimen.x24));
                break;

            case 1:
                drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x25),
                        getResources().getDimensionPixelSize(R.dimen.x25));
                break;
            case 2:
                drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x40),
                        getResources().getDimensionPixelSize(R.dimen.x25));
                break;
            case 3:
                drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x25),
                        getResources().getDimensionPixelSize(R.dimen.x25));
                break;
            case 4:
                drawables[1].setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.x25),
                        getResources().getDimensionPixelSize(R.dimen.x25));
                break;
            default:
                break;
            }

            radioBtns[i].setCompoundDrawables(drawables[0], drawables[1], drawables[2],
                    drawables[3]);//将改变了属性的drawable再重新设置回去
        }
        radioBtns[0].setChecked(true);
    }
  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值