Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change TextView Color Programmatically

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.

like image 883
tallpaul Avatar asked Mar 17 '16 11:03

tallpaul


2 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

like image 102
mgabz Avatar answered Sep 21 '22 05:09

mgabz


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);
like image 20
cricketycrack Avatar answered Sep 20 '22 05:09

cricketycrack