TextView的setCompoundDrawables和setCompoundDrawablesWithIntrinsicBounds的区别

摘要

我们都只TextView支持设置文字和图片同时显示,通常会联想到两种方法,一种是直接设置drawableXXX(Left, Top, Right, Bottom),四个方向的,还有一种是富文本的形式。
直接设置图片,要么是xml直接设置,要么是java类里面动态设置,但是在动态设置的时候,经常会直接采用setCompoundDrawables和setCompoundDrawablesWithIntrinsicBounds,但是这两个方法是有区别的。
看源码:

@android.view.RemotableViewMethod
    public void setCompoundDrawablesWithIntrinsicBounds(@Nullable Drawable left,
            @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) {

        if (left != null) {
            left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
        }
        if (right != null) {
            right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight());
        }
        if (top != null) {
            top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
        }
        if (bottom != null) {
            bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
        }
        setCompoundDrawables(left, top, right, bottom);
    }

看到源码之后,一目了然,setCompoundDrawablesWithIntrinsicBounds和setCompoundDrawables,就是前者先这只了资源的大小,然后调用setCompoundDrawables,去显示图片资源,
简而言之:
setCompoundDrawables 画的drawable的宽高是按drawable.setBound()设置的宽高,所以必须先设置drawable的宽高,在调用该方法,才会显示
setCompoundDrawablesWithIntrinsicBounds是画的drawable的宽高是按drawable固定的宽高,即:用
getIntrinsicWidth()与getIntrinsicHeight()获得

你可能感兴趣的:(TextView的setCompoundDrawables和setCompoundDrawablesWithIntrinsicBounds的区别)