安卓 TextView 设置Drawable大小

3,304 阅读1分钟

TextView Drawable

给自己看系列

TextView 可以使用android:drawableTop/Left/Right/Bottom属性在activity的xml中设置图片位置,但是不能控制drawable的大小,只能控制和文字之间的padding属性。

实现

通过继承TextView 重写 setCompoundDrawables 方法来控制Drawable大小

代码如下

/**
 * @description 
 * @author msp
 * @time 2021/3/17
 */
class BottomTabTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    override fun setCompoundDrawables(left: Drawable?, top: Drawable?, right: Drawable?, bottom: Drawable?) {
        top?.setBounds(0, 0, DisplayUtils.dp2px(this.context, 30f), DisplayUtils.dp2px(this.context, 30f))
        super.setCompoundDrawables(left, top, right, bottom)
    }

}

代码中的DisplayUtils工具类就是dp转px的工具