Home » Android » c# – How to change TextView Color Programmatically

c# – How to change TextView Color Programmatically

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

In 2017, this is somehow the correct way to get the color by resource id, even though it seems extremely convoluted:

new Android.Graphics.Color (ContextCompat.GetColor (this, Resource.Color.bb_orange));

per:
https://forums.xamarin.com/discussion/54193/res-getcolor-is-deprecated

Answer:

not needed to be so complex, just use

myTextView.setTextColor(Color.parseColor("#000"));

OR

 myTextView.setTextColor(Color.parseColor("red"));

OR

myTextView.setTextColor(getResources().getColor(R.color.YOURCOLOR));

Answer:

UPDATE

I first do not noticed it, but I see that you’ve tried this solution. What version are you using? In my it is not deprecated.

 textView.SetTextColor(Resources.GetColor(Resource.Color.red));

In Resources/values/colors.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <color name="red">#ff0000</color>
  <color name="blue">#0000ff</color>
</resources>

Xamarin Resource.Color

Answer:

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