※ 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}" />
以上です。