某些情况下,使用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);