Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the Color of a TextView Drawable

Im trying to change the color of a TextView Drawable in Xamarin.

In Java you can do it like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView txt = (TextView) findViewById(R.id.my_textview);
    setTextViewDrawableColor(txt, R.color.my_color);
}

private void setTextViewDrawableColor(TextView textView, int color) {
    for (Drawable drawable : textView.getCompoundDrawables()) {
        if (drawable != null) {
            drawable.setColorFilter(new PorterDuffColorFilter(getColor(color), PorterDuff.Mode.SRC_IN));
        }
    }
}

How i can do something like this in Xamarin.Android?

like image 778
CDrosos Avatar asked Apr 12 '17 12:04

CDrosos


People also ask

How do I change the drawable tint color in android programmatically?

imageView. setColorFilter(Color. argb(a, r, g, b));

How do I change the color of a drawable in xml?

Use app:drawableTint="@color/yourColor" in the xml instade android:drawableTint="@color/yourColor" . It has the backward compatibility.

How do I add background color to TextView?

To change the background color of TextView widget, set the background attribute with required Color value. You can specify color in rgb , argb , rrggbb , or aarrggbb formats. The background color is applied along the width and height of the TextView.


3 Answers

Try below solution

private void setTextViewDrawableColor(TextView textView, int color) {
        for (Drawable drawable : textView.getCompoundDrawables()) {
            if (drawable != null) {
                drawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(textView.getContext(), color), PorterDuff.Mode.SRC_IN));
            }
        }
    }
like image 174
Arthur Attout Avatar answered Oct 16 '22 08:10

Arthur Attout


I am using this in kotlin:

tv.getCompoundDrawables()[0].setTint(//color)
like image 37
Giedrius Šlikas Avatar answered Oct 16 '22 07:10

Giedrius Šlikas


Please, notice that if you set drawables in your layout file via android:drawableStart or android:drawableEnd instead of android:drawableLeft and android:drawableRight respectively you should use TextView.getCompoundDrawablesRelative(). Otherwise you can get empty array of drawables.

private void setTextViewDrawableColor(TextView textView, int color) {
    for (Drawable drawable : textView.getCompoundDrawablesRelative()) {
        if (drawable != null) {
            drawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(textView.getContext(), color), PorterDuff.Mode.SRC_IN));
        }
    }
}
like image 26
Nikita Yatskivskiy Avatar answered Oct 16 '22 09:10

Nikita Yatskivskiy