项目中遇到TextView setCompoundDrawables时不生效的情况。
不生效原因涉及到setCompoundDrawables的具体实现。
setCompoundDrawables源码如下:
/**
* Sets the Drawables (if any) to appear to the left of, above, to the
* right of, and below the text. Use {@code null} if you do not want a
* Drawable there. The Drawables must already have had
* {@link Drawable#setBounds} called.
* <p>
* Calling this method will overwrite any Drawables previously set using
* {@link #setCompoundDrawablesRelative} or related methods.
*
* @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(@Nullable Drawable left, @Nullable Drawable top,
@Nullable Drawable right, @Nullable Drawable bottom) {
注释中强调:
The Drawables must already have had
* {@link Drawable#setBounds} called.
所以setBounds(left, top, right, bottom)之后在设置setCompoundDrawables就可以显示出来了。