LoginSignup
19
14

More than 5 years have passed since last update.

API23未満でTextViewのDrawableにTintをかける

Last updated at Posted at 2017-02-13

※ API17の端末でTintがかからない問題があったので、サポートしているバージョンによってはこの方法は使えません。ちなみにAPI16では大丈夫でした。

TextViewにはAPI23以降で android:drawableTint があり、drawableの色を変更できます。API23未満の場合にもTintをかけたかったので、DataBindingで BindingAdapter を作って対応しました。

BindingAdapter

こんな感じで作っておきます。クラスはどこでもいいです。自分は BindingAdapter をまとめたクラスを作って置いています。

@BindingAdapter("drawableTintCompat")
public static void setDrawableTintCompat(TextView textView, int color) {
    Drawable[] drawables = textView.getCompoundDrawables();
    if (drawables.length == 0) {
        return;
    }

    for (int i = 0, size = drawables.length; i < size; i++) {
        Drawable drawable = drawables[i];
        if (drawable == null) {
            continue;
        }

        drawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(drawable, color);
        DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN);
        drawables[i] = drawable;
    }

    textView.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], drawables[2], drawables[3]);
}

Layout

使う時はこんな感じで指定します。

<TextView
    ...
    android:drawableLeft="@drawable/ic_edit_24"
    android:drawableStart="@drawable/ic_edit_24"
    android:text="@string/edit"
    app:drawableTintCompat="@{@color/grey3}" />

以上です。

19
14
1

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
19
14