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的工具,通過這種方法,可以設定drawable的大小位置。