LoginSignup
2
2

More than 3 years have passed since last update.

TextView の CompoundDrawable に ColorFilter をかける

Last updated at Posted at 2017-12-30

概要

Android の TextView に設定できる CompoundDrawable に ColorFilter をかけるやり方について述べます。

CompoundDrawable

TextView は CompoundDrawable という、テキストに隣接して表示させる画像を設定できます。

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/ic_drawable_white"
    />

これを用いると、ImageView と TextView を組み合わせる必要がなくなるのでレイアウト構成をシンプルにできます。表示させる位置はテキストの上下左右です。上記の例だと drawableLeft なので、テキストの左側に Drawable が表示されます。

ColorFilter をかける動機

私が作っているアプリで、ユーザにアプリ内View の色を自由に設定させる機能を入れていて、
ImageView を使っている箇所では白の Drawable を用意しそれに ColorFilter をかけるやり方でユーザの色設定を反映させる実装にしていました。

しかし、 CompoundDrawable の場合は ColorFilter をやり方を知らなかったので、Drawable の色がずっと白のままでした。

device-2017-12-22-210239.png


実装

実装方法

調べてみたらすぐにやり方が見つかりました。

Setting the Color of a TextView Drawable for Android

実装

記事のコードそのままでは芸がないので、別の書き方をしてみます。 Kotlin だと短く書けます。

textView.compoundDrawables?.forEach {
    it?.colorFilter = PorterDuffColorFilter(fontColor, PorterDuff.Mode.SRC_IN)
}

実装後

device-2017-12-22-210037.png

ご覧の通り、CompoundDrawable に ColorFilter がかかりました。

補足

ViewStub 内の TextView に対しては上手くいかなかったので、 TextViewCompat.setCompoundDrawableTintList を使った方が良いですね。

textView?.also {
    it.setTextColor(fontColor)
    TextViewCompat.setCompoundDrawableTintList(it, ColorStateList.valueOf(fontColor))
}

まとめ

CompoundDrawable に ColorFilter をかけたい場合、TextView の compoundDrawables からそれぞれの Drawable オブジェクトに実施すれば可能です。TextView を継承している Button 等でも同様に適用できます。

2
2
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
2