Setting the Color of a TextView Drawable

CDrosos picture CDrosos · Apr 12, 2017 · Viewed 16.6k times · Source

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?

Answer

Arthur Attout picture Arthur Attout · Apr 12, 2017

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));
            }
        }
    }