LoginSignup
2
1

More than 3 years have passed since last update.

TextViewのdrawableにsizeを設定してみる

Last updated at Posted at 2020-02-20
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

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1