class TextViewWithDrawable @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleInt: Int = 0
) : AppCompatTextView(context, attributeSet, defStyleInt) {
companion object {
@JvmStatic
@BindingAdapter(value = ["drawableStart", "drawableEnd", "drawableTop", "drawableBottom"], requireAll = false)
fun TextViewWithDrawable.setDrawable(drawableStart: Drawable? = null, drawableEnd: Drawable? = null, drawableTop: Drawable? = null, drawableBottom: Drawable? = null) {
val start = drawableStart?.setTextSizeBounds(this)
val end = drawableEnd?.setTextSizeBounds(this)
val top = drawableTop?.setTextSizeBounds(this)
val bottom = drawableBottom?.setTextSizeBounds(this)
setCompoundDrawables(start, top, end, bottom)
}
private fun Drawable.setTextSizeBounds(textView: TextView): Drawable = apply { setBounds(0, 0, textView.textSize.toInt(), textView.textSize.toInt()) }
}
TextViewのCustomViewを作成して、BindingAdapterを作ってあげます。
textViewのtext sizeに応じてdrawableのsizeを調整するようにしています。
使う側では、databindingなので、
<TextViewWithDrawable
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginEnd="16dp"
android:drawablePadding="2dp"
android:ellipsize="end"
android:lines="1"
android:text="あああ"
android:textColor="#444444"
android:textSize="11sp"
app:drawableStart="@{@drawable/icon}"/>
と、指定します。({}で囲うのを忘れない。)
ただし、CustomViewを作るとき、@JvmOverloadsを使うとThemeが反映されない場合があるみたいなので注意です。(今回は@JvmOverloadsを使用していますが)
https://medium.com/@mmlodawski/https-medium-com-mmlodawski-do-not-always-trust-jvmoverloads-5251f1ad2cfe