setCompoundDrawables 不能显示Drawable出来的问题。

某些情况下,使用setCompoundDrawables 不能显示出来应有的Drawable。

究其原因可能是因为没有设置Drawable边距。

通过设置bound,可以显示Drawble出来。

另一个办法是使用setCompoundDrawablesWithIntrinsicBounds。

setCompoundDrawables源码:

 /**
     * 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
     * {@link Drawable#setBounds} called.
     *
     * @attr ref android.R.styleable#TextView_drawableLeft
     * @attr ref android.R.styleable#TextView_drawableTop
     * @attr ref android.R.styleable#TextView_drawableRight
     * @attr ref android.R.styleable#TextView_drawableBottom
     */
    public void setCompoundDrawables(Drawable left, Drawable top,
                                     Drawable right, Drawable bottom) {

....}

翻译过来就是Drawble必须已经设置了bounds:

可在使用setCompoundDrawables前,设置Drawable的Bound。

所以可以这样做:

Drawable mDrawable= res.getDrawable(R.drawable.home);
mDrawable.setBounds(1, 1, 100, 100);
button.setCompoundDrawables(null, mDrawable, null, null);
这个方法的好处是 图片会根据设置的边距来显示大小。缺点就是可能会变形。
如果不想图片变形,用setCompoundDrawablesWithIntrinsicBounds更加方便。使用这个方法Drawable会根据Drawable自身的大小去显示。
   /**
     * 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' bounds will be set to
     * their intrinsic bounds.
     *
     * @attr ref android.R.styleable#TextView_drawableLeft
     * @attr ref android.R.styleable#TextView_drawableTop
     * @attr ref android.R.styleable#TextView_drawableRight
     * @attr ref android.R.styleable#TextView_drawableBottom
     */
    public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
            Drawable right, Drawable bottom) {...}
The Drawables' bounds will be set to their intrinsic bounds.
翻译过来就是Drawable按照固有的边距去显示。
直接
Drawable mDrawable= res.getDrawable(R.drawable.home);
button.setCompoundDrawablesWithIntrinsicBounds(null, mDrawable, null, null);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值