Setting the Color of a TextView Drawable
Solution 1
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));
}
}
}
Solution 2
I am using this in kotlin:
tv.getCompoundDrawables()[0].setTint(//color)
Solution 3
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));
}
}
}
Solution 4
// index of drawable
val left = 0
val start = left
val top = 1
val right = 2
val end = right
val bottm = 3
// color int
val color = Color.RED
// apply tint for target drawable
textView.compoundDrawables.getOrNull(left)?.setTint(color)
// apply tint for all drawables
textView.compoundDrawables?.forEach { it?.setTint(color) }
NOTE!
if in XML layout you use android:stratDrawable
or android:endDrawable
you have to work with textView.compoundDrawablesRelative
array, textView.compoundDrawables
contains drawables when they have been added with android:leftDrawable
or android:rightDrawable
attributes.
Solution 5
I solve this problem adding in xml definition this line:
android:drawableTint="@color/red"
A complete example:
<TextView android:id="@+id/tv_element" android:layout_width="wrap_content" android:layout_height="20dp" android:layout_alignParentEnd="true" android:drawableStart="@drawable/ic_icon" android:drawableTint="@color/color" android:visibility="visible" />
CDrosos
Gym and Movie Lover! C#, PHP, HTML Programmer and Web Developer. Some of my Works: https://alkodi.gr https://cactus-eshop.gr https://peinirli.gr/ https://forevertravel.gr/ You can support me here: https://www.buymeacoffee.com/chrisdrosos
Updated on January 19, 2022Comments
-
CDrosos over 2 years
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?