How to change TextView Color Programmatically

Viewed 13885

I am stumped with this seemingly simple task.

I want to simply change the color of a textview and the background color of a linearlayout to colors set in my colors.xml resource file.

I have tried:

myTextView.SetTextColor(this.Resources.GetColor(Resource.Color.myColor));

But this is deprecated.

I then tried:

myTextView.SetTextColor(ContextCompat.GetColor(context, Resource.Color.myColor));

But ContextCompat.GetColor() returns an int rather than an Android.Graphics.Color so won't compile.

I then tried to instead set the color as part of a style:

  <style name="myColorStyle">
    <item name="android:textColor">
      @color/myColor
    </item>
...
  </style>

and set it first using

myTextView.SetTextAppearance(this, Resource.Style.myColorStyle);

but this is also deprecated so

I tried this:

myTextView.SetTextAppearance(Resource.Style.myColorStyle);

but this throws an exception:

Java.Lang.NoSuchMethodError: no non-static method "Landroid/widget/TextView;.setTextAppearance(I)V"

How is this simple task achieved?

I am coding in C# using Xamarin and Visual Studio.

4 Answers

Its quite simple, if you want to skip the xml.

  myTextView.SetTextColor(Android.Graphics.Color.Red);

Also works for setting the background color of the text view.

myTextView.SetBackgroundColor(Android.Graphics.Color.White);
Related